GVPR(1)
π GVPR(1) π
okay bestie, this is the manual for gvpr β graph pattern scanning and processing language. It's giving graph stream editor, awk-inspired, and we're about to read the whole thing together. π
β¨ NAME β¨
gvpr β graph pattern scanning and processing language
πΈ SYNOPSIS πΈ
gvpr [-icnqV?] [ -o outfile ] [ -a args ] [ 'prog' | -f progfile ] [ files ]
π¦ DESCRIPTION π¦
gvpr (previously known as gpr) is a graph stream editor inspired by awk. It copies input graphs to its output, possibly transforming their structure and attributes, creating new graphs, or printing arbitrary information. The graph model is that provided by libcgraph(3). In particular, gvpr reads and writes graphs using the dot language.
Basically, gvpr traverses each input graph, denoted by $G, visiting each node and edge, matching it with the predicate-action rules supplied in the input program. The rules are evaluated in order. For each predicate evaluating to true, the corresponding action is performed. During the traversal, the current node or edge being visited is denoted by $.
For each input graph, there is a target subgraph, denoted by $T, initially empty and used to accumulate chosen entities, and an output graph, $O, used for final processing and then written to output. By default, the output graph is the target graph. The output graph can be set in the program or, in a limited sense, on the command line.
π OPTIONS π
The following options are supported:
-aargs β The string args is split into whitespace-separated tokens, with the individual tokens available as strings in thegvprprogram asARGV[0],...,ARGV[ARGC-1]. Whitespace characters within single or double quoted substrings, or preceded by a backslash, are ignored as separators. In general, a backslash character turns off any special meaning of the following character. Note that the tokens derived from multiple-aflags are concatenated.-cβ Use the source graph as the output graph.-iβ Derive the node-induced subgraph extension of the output graph in the context of its root graph.-ooutfile β Causes the output stream to be written to the specified file; by default, output is written tostdout.-fprogfile β Use the contents of the specified file as the program to execute on the input. If progfile contains a slash character, the name is taken as the pathname of the file. Otherwise,gvprwill use the directories specified in the environment variableGVPRPATHto look for the file. If-fis not given,gvprwill use the first non-option argument as the program.-qβ Turns off warning messages.-nβ Turns off graph read-ahead. By default, the variable$NGis set to the next graph to be processed. This requires a read of the next graph before processing the current graph, which may block if the next graph is only generated in response to some action pertaining to the processing of the current graph.-vβ Enable verbose messages.-Vβ Causes the program to print version information and exit.-?β Causes the program to print usage information and exit.
π OPERANDS π
The following operand is supported:
- files β Names of files containing 1 or more graphs in the dot language. If no
-foption is given, the first name is removed from the list and used as the input program. If the list of files is empty,stdinwill be used.
π PROGRAMS π
A gvpr program consists of a list of predicate-action clauses, having one of the forms:
BEGIN { action }
BEG_G { action }
N [ predicate ] { action }
E [ predicate ] { action }
END_G { action }
END { action }
A program can contain at most one of each of the BEGIN, END_G and END clauses. There can be any number of BEG_G, N and E statements, the first applied to graphs, the second to nodes, the third to edges. These are separated into blocks, a block consisting of an optional BEG_G statement and all N and E statements up to the next BEG_G statement, if any. The top-level semantics of a gvpr program are:
Evaluate the BEGIN clause, if any.
For each input graph G {
For each block {
Set G as the current graph and current object.
Evaluate the BEG_G clause, if any.
For each node and edge in G {
Set the node or edge as the current object.
Evaluate the N or E clauses, as appropriate.
}
}
Set G as the current object.
Evaluate the END_G clause, if any.
}
Evaluate the END clause, if any.
The actions of the BEGIN, BEG_G, END_G and END clauses are performed when the clauses are evaluated. For N or E clauses, either the predicate or action may be omitted. If there is no predicate with an action, the action is performed on every node or edge, as appropriate. If there is no action and the predicate evaluates to true, the associated node or edge is added to the target graph.
The blocks are evaluated in the order in which they occur. Within a block, the N clauses (E clauses, respectively) are evaluated in the order in which they occur. Note, though, that within a block, N or E clauses may be interlaced, depending on the traversal order.
Predicates and actions are sequences of statements in the C dialect supported by the expr(3) library. The only difference between predicates and actions is that the former must have a type that may interpreted as either true or false. Here the usual C convention is followed, in which a non-zero value is considered true. This would include non-empty strings and non-empty references to nodes, edges, etc. However, if a string can be converted to an integer, this value is used.
In addition to the usual C base types (void, int, char, float, long, unsigned and double), gvpr provides string as a synonym for char*, and the graph-based types node_t, edge_t, graph_t and obj_t. The obj_t type can be viewed as a supertype of the other 3 concrete types; the correct base type is maintained dynamically. Besides these base types, the only other supported type expressions are (associative) arrays.
Constants follow C syntax, but strings may be quoted with either "..." or '...'. gvpr accepts C++ comments as well as cpp-type comments. For the latter, if a line begins with a '#' character, the rest of the line is ignored.
A statement can be a declaration of a function, a variable or an array, or an executable statement. For declarations, there is a single scope. Array declarations have the form:
type array [ type0 ]
where type0 is optional. If it is supplied, the parser will enforce that all array subscripts have the specified type. If it is not supplied, objects of all types can be used as subscripts. As in C, variables and arrays must be declared. In particular, an undeclared variable will be interpreted as the name of an attribute of a node, edge or graph, depending on the context.
Executable statements can be one of the following:
{ [ statement ... ] }
expression // commonly var = expression
if( expression ) statement [ else statement ]
for( expression ; expression ; expression ) statement
for( array [ var ]) statement
forr( array [ var ]) statement
while( expression ) statement
switch( expression ) case statements
break [ expression ]
continue [ expression ]
return [ expression ]
Items in brackets are optional.
In the second form of the for statement and the forr statement, the variable var is set to each value used as an index in the specified array and then the associated statement is evaluated. For numeric and string indices, the indices are returned in increasing (decreasing) numeric or lexicographic order for for (forr, respectively). This can be used for sorting.
Function definitions can only appear in the BEGIN clause.
Expressions include the usual C expressions. String comparisons using == and != treat the right hand operand as a pattern for the purpose of regular expression matching. Patterns use ksh(1) file match pattern syntax. (For simple string equality, use the strcmp function.
gvpr will attempt to use an expression as a string or numeric value as appropriate. Both C-like casts and function templates will cause conversions to be performed, if possible.
Expressions of graphical type (i.e., graph_t, node_t, edge_t, obj_t) may be followed by a field reference in the form of .name. The resulting value is the value of the attribute named name of the given object. In addition, in certain contexts an undeclared, unmodified identifier is taken to be an attribute name. Specifically, such identifiers denote attributes of the current node or edge, respectively, in N and E clauses, and the current graph in BEG_G and END_G clauses.
As usual in the libcgraph(3) model, attributes are string-valued. In addition, gvpr supports certain pseudo-attributes of graph objects, not necessarily string-valued. These reflect intrinsic properties of the graph objects and cannot be set by the user.
head:node_tβ the head of an edge.tail:node_tβ the tail of an edge.name:stringβ the name of an edge, node or graph. The name of an edge has the form"<tail-name><edge-op><head-name>[<key>]", where<edge-op>is"->"or"--"depending on whether the graph is directed or not. The bracket part[<key>]only appears if the edge has a non-trivial key.indegree:intβ the indegree of a node.outdegree:intβ the outdegree of a node.degree:intβ the degree of a node.X:doubleβ the X coordinate of a node. (Assumes the node has aposattribute.)Y:doubleβ the Y coordinate of a node. (Assumes the node has aposattribute.)root:graph_tβ the root graph of an object. The root of a root graph is itself.parent:graph_tβ the parent graph of a subgraph. The parent of a root graph isNULLn_edges:intβ the number of edges in the graphn_nodes:intβ the number of nodes in the graphdirected:intβ true (non-zero) if the graph is directedstrict:intβ true (non-zero) if the graph is strict
π BUILT-IN FUNCTIONS π
The following functions are built into gvpr. Those functions returning references to graph objects return NULL in case of failure.
πΈ Graphs and subgraph πΈ
okay bestie, these are the graph-level functions that make graphs, subgraphs, and tell you stuff about them. slay.
graph(s : string, t : string) : graph_tβ creates a graph whose name issand whose type is specified by the stringt. Ignoring case, the charactersU,D,S,Nhave the interpretation undirected, directed, strict, and non-strict, respectively. Iftis empty, a directed, non-strict graph is generated.subg(g : graph_t, s : string) : graph_tβ creates a subgraph in graphgwith names. If the subgraph already exists, it is returned. no cap.isSubg(g : graph_t, s : string) : graph_tβ returns the subgraph in graphgwith names, if it exists, orNULLotherwise.fstsubg(g : graph_t) : graph_tβ returns the first subgraph in graphg, orNULLif none exists.nxtsubg(sg : graph_t) : graph_tβ returns the next subgraph aftersg, orNULL.isDirect(g : graph_t) : intβ returns true if and only ifgis directed. periodt.isStrict(g : graph_t) : intβ returns true if and only ifgis strict.nNodes(g : graph_t) : intβ returns the number of nodes ing.nEdges(g : graph_t) : intβ returns the number of edges ing.
π¦ Nodes π¦
nodes are the main characters, fr fr. hereβs how to make them and vibe-check them.
node(g : graph_t, s : string) : node_tβ creates a node in graphgof names. If such a node already exists, it is returned.subnode(sg : graph_t, n : node_t) : node_tβ inserts the nodeninto the subgraphsg. Returns the node.fstnode(g : graph_t) : node_tβ returns the first node in graphg, orNULLif none exists.nxtnode(n : node_t) : node_tβ returns the next node afternin the root graph, orNULL.nxtnode_sg(sg : graph_t, n : node_t) : node_tβ returns the next node afterninsg, orNULL.isNode(sg : graph_t, s : string) : node_tβ looks for a node in (sub)graphsgof names. If such a node exists, it is returned. Otherwise,NULLis returned.isSubnode(sg : graph_t, n : node_t) : intβ returns non-zero if nodenis in (sub)graphsg, or zero otherwise.indegreeOf(sg : graph_t, n : node_t) : intβ returns the indegree of nodenin (sub)graphsg.outdegreeOf(sg : graph_t, n : node_t) : intβ returns the outdegree of nodenin (sub)graphsg.degreeOf(sg : graph_t, n : node_t) : intβ returns the degree of nodenin (sub)graphsg.rename(n : node_t, newname : string) : intβ changes the name ofntonewnameand returns0on success or-1if there is an existing node with that name.
π Edges π
edges connect the girlies. hereβs the whole edge situation.
edge(t : node_t, h : node_t, s : string) : edge_tβ creates an edge with tail nodet, head nodehand namesin the root graph. If the graph is undirected, the distinction between head and tail nodes is unimportant. If such an edge already exists, it is returned.edge_sg(sg : graph_t, t : node_t, h : node_t, s : string) : edge_tβ creates an edge with tail nodet, head nodehand namesin (sub)graphsg(and all parent graphs). If the graph is undirected, the distinction between head and tail nodes is unimportant. If such an edge already exists, it is returned.subedge(g : graph_t, e : edge_t) : edge_tβ inserts the edgeeinto the subgraphg. Returns the edge.isEdge(t : node_t, h : node_t, s : string) : edge_tβ looks for an edge with tail nodet, head nodehand names. If the graph is undirected, the distinction between head and tail nodes is unimportant. If such an edge exists, it is returned. Otherwise,NULLis returned.isEdge_sg(sg : graph_t, t : node_t, h : node_t, s : string) : edge_tβ looks for an edge with tail nodet, head nodehand namesin (sub)graphsg. If the graph is undirected, the distinction between head and tail nodes is unimportant. If such an edge exists, it is returned. Otherwise,NULLis returned.isSubedge(sg : graph_t, e : edge_t) : intβ returns non-zero if edgeeis in (sub)graphsg, or zero otherwise.fstout(n : node_t) : edge_tβ returns the first outedge of nodenin the root graph.fstout_sg(sg : graph_t, n : node_t) : edge_tβ returns the first outedge of nodenin (sub)graphsg.nxtout(e : edge_t) : edge_tβ returns the next outedge afterein the root graph.nxtout_sg(sg : graph_t, e : edge_t) : edge_tβ returns the next outedge afterein graphsg.fstin(n : node_t) : edge_tβ returns the first inedge of nodenin the root graph.fstin_sg(sg : graph_t, n : node_t) : edge_tβ returns the first inedge of nodenin graphsg.nxtin(e : edge_t) : edge_tβ returns the next inedge afterein the root graph.nxtin_sg(sg : graph_t, e : edge_t) : edge_tβ returns the next inedge afterein graphsg.fstedge(n : node_t) : edge_tβ returns the first edge of nodenin the root graph.fstedge_sg(sg : graph_t, n : node_t) : edge_tβ returns the first edge of nodenin graphsg.nxtedge(e : edge_t, n : node_t) : edge_tβ returns the next edge afterein the root graph.nxtedge_sg(sg : graph_t, e : edge_t, n : node_t) : edge_tβ returns the next edge afterein the graphsg.opp(e : edge_t, n : node_t) : node_tβ returns the node on the edgeenot equal ton. ReturnsNULLifnis not a node ofe. This can be useful when usingfstedgeandnxtedgeto enumerate the neighbors ofn. π
πΎ Graph I/O πΎ
reading and writing graphs, the moment weβve all been waiting for.
write(g : graph_t) : voidβ printsgin dot format onto the output stream.writeG(g : graph_t, fname : string) : voidβ printsgin dot format into the filefname.fwriteG(g : graph_t, fd : int) : voidβ printsgin dot format onto the open stream denoted by the integerfd.readG(fname : string) : graph_tβ returns a graph read from the filefname. The graph should be in dot format. If no graph can be read,NULLis returned.freadG(fd : int) : graph_tβ returns the next graph read from the open streamfd. ReturnsNULLat end of file.
π Graph miscellany π
the catch-all drawer of graph stuff. itβs giving very useful, ngl.
delete(g : graph_t, x : obj_t) : voidβ deletes objectxfrom graphg. IfgisNULL, the function uses the root graph ofx. Ifxis a graph or subgraph, it is closed unlessxis locked.isIn(g : graph_t, x : obj_t) : intβ returns true ifxis in subgraphg.cloneG(g : graph_t, s : string) : graph_tβ creates a clone of graphgwith name ofs. Ifsis"", the created graph has the same name asg.clone(g : graph_t, x : obj_t) : obj_tβ creates a clone of objectxin graphg. In particular, the new object has the same name/value attributes and structure as the original object. If an object with the same key asxalready exists, its attributes are overlaid by those ofxand the object is returned. If an edge is cloned, both endpoints are implicitly cloned. If a graph is cloned, all nodes, edges and subgraphs are implicitly cloned. Ifxis a graph,gmay beNULL, in which case the cloned object will be a new root graph. In this case, the call is equivalent tocloneG(x,"").copy(g : graph_t, x : obj_t) : obj_tβ creates a copy of objectxin graphg, where the new object has the same name/value attributes as the original object. If an object with the same key asxalready exists, its attributes are overlaid by those ofxand the object is returned. Note that this is a shallow copy. Ifxis a graph, none of its nodes, edges or subgraphs are copied into the new graph. Ifxis an edge, the endpoints are created if necessary, but they are not cloned. Ifxis a graph,gmay beNULL, in which case the cloned object will be a new root graph.copyA(src : obj_t, tgt : obj_t) : intβ copies the attributes of objectsrcto objecttgt, overwriting any attribute valuestgtmay initially have.induce(g : graph_t) : voidβ extendsgto its node-induced subgraph extension in its root graph.hasAttr(src : obj_t, name : string) : intβ returns non-zero if objectsrchas an attribute whose name isname. It returns0otherwise.isAttr(g : graph_t, kind : string, name : string) : intβ returns non-zero if an attributenamehas been defined ingfor objects of the given kind. For nodes, edges, and graphs,kindshould be"N","E", and"G", respectively. It returns0otherwise.aget(src : obj_t, name : string) : stringβ returns the value of attributenamein objectsrc. This is useful for those cases whennameconflicts with one of the keywords such as"head"or"root". If the attribute has not been declared in the graph, the function will initialize it with a default value of"". To avoid this, one should use thehasAttrorisAttrfunction to check that the attribute exists.aset(src : obj_t, name : string, value : string) : intβ sets the value of attributenamein objectsrctovalue. Returns0on success, non-zero on failure. Seeagetabove.getDflt(g : graph_t, kind : string, name : string) : stringβ returns the default value of attributenamein objects ingof the given kind. For nodes, edges, and graphs,kindshould be"N","E", and"G", respectively. If the attribute has not been declared in the graph, the function will initialize it with a default value of"". To avoid this, one should use theisAttrfunction to check that the attribute exists.setDflt(g : graph_t, kind : string, name : string, value : string) : intβ sets the default value of attributenametovaluein objects ingof the given kind. For nodes, edges, and graphs,kindshould be"N","E", and"G", respectively. Returns0on success, non-zero on failure. SeegetDfltabove.fstAttr(g : graph_t, kind : string) : stringβ returns the name of the first attribute of objects ingof the given kind. For nodes, edges, and graphs,kindshould be"N","E", and"G", respectively. If there are no attributes, the string""is returned.nxtAttr(g : graph_t, kind : string, name : string) : stringβ returns the name of the next attribute of objects ingof the given kind after the attributename. The argumentnamemust be the name of an existing attribute; it will typically be the return value of an previous call tofstAttrornxtAttr. For nodes, edges, and graphs,kindshould be"N","E", and"G", respectively. If there are no attributes left, the string""is returned.compOf(g : graph_t, n : node_t) : graph_tβ hands you back the connected component of graphgthat contains noden, as a subgraph ofg. Heads up bestie: this subgraph is nodes only, no edges. You gotta runinduceif you want the edges back in. Ifnisn't even ing, it fails and returnsNULL. And "connected" here means connected in the underlying undirected graph ofg. π¦kindOf(obj : obj_t) : stringβ tells you what kind of thingobjis. For nodes it's"N", for edges"E", for graphs"G". Cute lil single-letter vibes. β¨lock(g : graph_t, v : int) : intβ graph locking, but only on root graphs. Ifvis positive, the graph gets locked so futuredeletecalls don't take effect immediately. Ifvis zero, it's unlocked. And if somebody calleddeleteon the graph while it was locked? The graph gets closed. Ifvis negative, literally nothing happens. Either way, you get the previous lock value back. π
πΈ Strings πΈ
sprintf(fmt : string, ...) : stringβ returns the string you get from formatting everything afterfmtaccording to theprintf(3)formatfmt. Classic glow-up for your values. β¨gsub(str : string, pat : string) : stringgsub(str : string, pat : string, repl : string) : stringβ gives youstrwith all the substrings matchingpatdeleted, or replaced byrepl. Global search and destroy, no cap. π₯sub(str : string, pat : string) : stringsub(str : string, pat : string, repl : string) : stringβ same energy but only the leftmost substring matchingpatgets deleted or replaced byrepl. You can also use'^'and'$'at the beginning and end ofpatto anchor the pattern to the start or end ofstr, respectively. πsubstr(str : string, idx : int) : stringsubstr(str : string, idx : int, len : int) : stringβ the substring ofstrfrom positionidxto the end, or of lengthlen. Indexing starts at0btw, we're not barbarians. Ifidxis negative oridxis greater than the length ofstr, it's a fatal error. Same deal in the second form: iflenis negative oridx + lenis greater than the length ofstr, fatal error. Be careful bestie. πstrcmp(s1 : string, s2 : string) : intβ it's the standard Cstrcmp(3), doing exactly what you expect. π«Άlength(s : string) : intβ the length of strings. Periodt. πindex(s : string, t : string) : intrindex(s : string, t : string) : intβ gives you the index inswhere the leftmost (or rightmost) copy oftlives, or-1iftisn't a substring ofs. Finder of strings, iconic. π¦match(s : string, p : string) : intβ the index inswhere the leftmost match of patternpstarts, or-1if no substring ofsmatchesp. Regex bestie behavior. β¨toupper(s : string) : stringβ a version ofswith the alphabetic characters screamed into UPPER-CASE. π£tolower(s : string) : stringβ a version ofswith the alphabetic characters softened into lower-case. πΈcanon(s : string) : stringβ a version ofsthat's fit to be used as an identifier in a dot file. Cleaned up and ready to serve. πhtml(g : graph_t, s : string) : stringβ returns a "magic" version ofsas an HTML string. You'd typically use this to attach an HTML-like label to a graph object. Important tea though: the returned string lives ing. So it gets freed whengis closed, and to actually act as an HTML string it has to be used with an object ofg. Also the angle bracket quotes should not be part ofsβ those get added ifgis written in concrete DOT format. πishtml(s : string) : intβ returns non-zero if and only ifsis an HTML string. Simple vibe check. β¨xOf(s : string) : stringβ returns the string"x"ifshas the form"x,y", where bothxandyare numeric. πyOf(s : string) : stringβ returns the string"y"ifshas the form"x,y", where bothxandyare numeric. Matching set bestie. πllOf(s : string) : stringβ returns the string"llx,lly"ifshas the form"llx,lly,urx,ury", where all ofllx,lly,urx, anduryare numeric. πurOf(s)urOf(s : string) : stringβ returns the string"urx,ury"ifshas the form"llx,lly,urx,ury", where all ofllx,lly,urx, anduryare numeric. πsscanf(s : string, fmt : string, ...) : intβ scans the strings, pulling out values according to thesscanf(3)formatfmt. The values get stored in the addresses followingfmt, and those addresses have the form&v, wherevis some declared variable of the correct type. Returns how many items it successfully scanned. πsplit(s : string, arr : array, seps : string) : intsplit(s : string, arr : array) : inttokens(s : string, arr : array, seps : string) : inttokens(s : string, arr : array) : intβ okay sosplitbreaks the stringsinto fields, whiletokensbreaks it into tokens. A field is all the non-separator characters between two separator characters (or the beginning/end of the string) β which means a field can totally be the empty string, no judgment. A token is a maximal, non-empty substring that doesn't contain a separator character. The separator characters are whatever you put inseps. If you don't provideseps, the default is" \t\n". The functions return the number of fields or tokens. π
The fields and tokens get stored in the argument arr. That array must be string-valued and have int as its index type. Entries are indexed by consecutive integers starting at 0. Anything already sitting in the array will either be overwritten, or still be present after the function returns. β¨
π» I/O π»
print(...) : voidβprint( expr, ... )prints a string representation of each argument in turn ontostdout, followed by a newline. Say it with your chest. π£printf(fmt : string, ...) : intprintf(fd : int, fmt : string, ...) : intβ prints the string you get from formatting the values afterfmtaccording to theprintf(3)formatfmt. Returns0on success. By default it prints onstdout. If you pass the optional integerfd, output is written on the open stream associated withfd. Serving formatted text fr fr. πscanf(fmt : string, ...) : intscanf(fd : int, fmt : string, ...) : intβ scans values from an input stream according to thescanf(3)formatfmt. Values get stored in the addresses followingfmt, addresses of the form&v, wherevis a declared variable of the correct type. By default it reads fromstdin. If the optional integerfdis given, input is read from the open stream associated withfd. Returns the number of items successfully scanned. π«ΆopenF(s : string, t : string) : intβ opens the filesas an I/O stream. The string argumenttsays how the file gets opened. The arguments are the same as for the C functionfopen(3). Returns an integer denoting the stream, or-1on error. π¦
As usual, streams 0, 1 and 2 are already open as stdin, stdout, and stderr, respectively. But since gvpr may use stdin to read the input graphs, the user should avoid using this stream. You've been warned bestie. π
closeF(fd : int) : intβ closes the open stream denoted by the integerfd. Streams0,1and2cannot be closed. Returns0on success. πreadL(fd : int) : stringβ returns the next line read from the input streamfd. Returns the empty string""on end of file. Note that the newline character is left in the returned string, so don't be surprised by it. πΈ
β Math β
exp(d : double) : doubleβ returnseto thedth power. πlog(d : double) : doubleβ returns the natural log ofd. πΏsqrt(d : double) : doubleβ returns the square root of the doubled. ββ¨pow(d : double, x : double) : doubleβ returnsdraised to thexth power. π₯cos(d : double) : doubleβ returns the cosine ofd. πsin(d : double) : doubleβ returns the sine ofd. πatan2(y : double, x : double) : doubleβ returns the arctangent ofy/xin the range-pitopi. πMIN(y : double, x : double) : doubleβ returns the minimum ofyandx. π₯MAX(y : double, x : double) : doubleβ returns the maximum ofyandx. π
π Associative Arrays π
# arr : intβ returns the number of elements in the arrayarr. Hashtag it, count it, slay. πidx in arr : intβ returns1if a value has been set for indexidxin the arrayarr. Returns0otherwise. Vibe check on that index. β¨unset(v : array, idx) : intβ removes the item indexed byidx. Returns1if the item existed,0otherwise. π§unset(v : array) : voidβ re-initializes the array. Full reset, fresh start. πΈ
β¨ Miscellaneous β¨
exit(v : int) : voidβ causesgvprto exit with the exit codev. Bye bestie, on your terms. πsystem(cmd : string) : intβ provides the standard C functionsystem(3). It executescmdin the user's shell environment, and returns the exit status of the shell. Main character energy, running the whole show. π₯rand() : doubleβ returns a pseudo-random double between0and1. π²srand() : intsrand(v : int) : intβ sets a seed for the random number generator. The optional argument gives the seed; if you leave it out, the current time is used. Returns the previous seed value.srandshould be called before any calls torandβ that's the rule, don't skip it. πcolorx(color : string, fmt : string) : stringβ translates a color from one format to another. Thecolorargument should be a color in one of the recognized string representations. Thefmtvalue should be one of"RGB","RGBA","HSV", or"HSVA". Returns an empty string on error. The glow-up pipeline for your color palette. π
β¨ BUILTβIN VARIABLES β¨
okay bestie so gvpr comes with a whole lil squad of special variables that are basically the main characters π«Ά β it sets their values for you automatically depending on the context. And unless it says otherwise, you cannot change them. iykyk.
$:obj_tβ this is the current object, whether that's a node, an edge, or a graph, depending on the context. Heads up though: it is not available inBEGINorENDclauses. π$F:stringβ the name of the current input file, periodt.$G:graph_tβ the current graph being processed. Again, not available inBEGINorENDclauses. π$NG:graph_tβ the next graph to be processed. If$NGisNULL, then the current graph$Gis the last graph. Lowkey important caveat: if the input comes fromstdin, the last graph cannot be determined until the input pipe is closed. It is not available inBEGINorENDclauses, or if the-nflag is used. π$O:graph_tβ the output graph. Before graph traversal it gets initialized to the target graph. After traversal and anyEND_Gactions, if it refers to a non-empty graph, that graph is printed onto the output stream. It is only valid inN,EandEND_Gclauses. And yes β the output graph may be set by the user. π$T:graph_tβ the current target graph. It's a subgraph of$G, and it's available only inN,EandEND_Gclauses.$tgtname:stringβ the name of the target graph. By default it's set to"gvpr_result". If used multiple times during the execution ofgvpr, the name will be appended with an integer. This variable may be set by the user. π$tvroot:node_tβ the starting node for a (directed or undirected) depth-first or breadth-first traversal of the graph (cf.$tvtypebelow). The default value isNULLfor each input graph. After the traversal at the given root, if the value of$tvroothas changed, a new traversal will begin with the new value of$tvroot. Also, see$tvnextbelow.$tvnext:node_tβ the next starting node for a (directed or undirected) depth-first or breadth-first traversal of the graph (cf.$tvtypebelow). If a traversal finishes and the$tvroothas not been reset but the$tvnexthas been set but not used, this node will be used as the next choice for$tvroot. The default value isNULLfor each input graph.$tvedge:edge_tβ for BFS and DFS traversals, this is set to the edge used to arrive at the current node or edge. At the beginning of a traversal, or for other traversal types, the value isNULL.$tvtype:tvtype_tβ tells you howgvprtraverses a graph. It can only take one of the constant values with the prefixTV_described below.TV_flatis the default.
In the underlying graph library cgraph(3), edges in undirected graphs are given an arbitrary direction. This is used for traversals, such as TV_fwd, requiring directed edges. π¦
ARGC:intβ the number of arguments specified by the-aargs command-line argument.ARGV:string arrayβ the array of arguments specified by the-aargs command-line argument. The *i*th argument is given byARGV[i]. β¨
π BUILTβIN CONSTANTS π
There are several symbolic constants defined by gvpr. The whole collection, no cap:
NULL:obj_tβ a null object reference, equivalent to0.TV_flat:tvtype_tβ a simple, flat traversal, with graph objects visited in seemingly arbitrary order.TV_ne:tvtype_tβ a traversal which first visits all of the nodes, then all of the edges.TV_en:tvtype_tβ a traversal which first visits all of the edges, then all of the nodes.TV_dfs:tvtype_tTV_postdfs:tvtype_tTV_prepostdfs:tvtype_t
β a traversal of the graph using a depth-first search on the underlying undirected graph. To do the traversal, gvpr will check the value of $tvroot. If this has the same value that it had previously (at the start, the previous value is initialized to NULL.), gvpr will simply look for some unvisited node and traverse its connected component. On the other hand, if $tvroot has changed, its connected component will be toured, assuming it has not been previously visited or, if $tvroot is NULL, the traversal will stop. Note that using TV_dfs and $tvroot, it is possible to create an infinite loop. π
By default, the traversal is done in pre-order. That is, a node is visited before all of its unvisited edges. For TV_postdfs, all of a node's unvisited edges are visited before the node. For TV_prepostdfs, a node is visited twice, before and after all of its unvisited edges.
TV_fwd:tvtype_tTV_postfwd:tvtype_tTV_prepostfwd:tvtype_t
β a traversal of the graph using a depth-first search on the graph following only forward arcs. The choice of roots for the traversal is the same as described for TV_dfs above. The different order of visitation specified by TV_fwd, TV_postfwd and TV_prepostfwd are the same as those specified by the analogous traversals TV_dfs, TV_postdfs and TV_prepostdfs. π₯
TV_rev:tvtype_tTV_postrev:tvtype_tTV_prepostrev:tvtype_t
β a traversal of the graph using a depth-first search on the graph following only reverse arcs. The choice of roots for the traversal is the same as described for TV_dfs above. The different order of visitation specified by TV_rev, TV_postrev and TV_prepostrev are the same as those specified by the analogous traversals TV_dfs, TV_postdfs and TV_prepostdfs. π
TV_bfs:tvtype_tβ a traversal of the graph using a breadth-first search on the graph ignoring edge directions. See the item onTV_dfsabove for the role of$tvroot. π§
π EXAMPLES π
okay these are literally so good, watch this:
gvpr -i 'N[color=="blue"]' file.gv
Generate the node-induced subgraph of all nodes with color blue. π
gvpr -c 'N[color=="blue"]{color = "red"}' file.gv
Make all blue nodes red. iconic transformation fr fr.
BEGIN { int n, e; int tot_n = 0; int tot_e = 0; }
BEG_G {
n = nNodes($G);
e = nEdges($G);
printf ("%d nodes %d edges %s\n", n, e, $G.name);
tot_n += n;
tot_e += e;
}
END { printf ("%d nodes %d edges total\n", tot_n, tot_e) }
Version of the program gc.
BEG_G { graph_t g = graph ("merge", "S"); }
E {
node_t h = clone(g,$.head);
node_t t = clone(g,$.tail);
edge_t e = edge(t,h,"");
e.weight = e.weight + 1;
}
END_G { $O = g; }
Produces a strict version of the input graph, where the weight attribute of an edge indicates how many edges from the input graph the edge represents. π€―
BEGIN {node_t n; int deg[]}
E{deg[head]++; deg[tail]++; }
END_G {
for (deg[n]) {
printf ("deg[%s] = %d\n", n.name, deg[n]);
}
}
Computes the degrees of nodes with edges.
BEGIN {
int i, indent;
int seen[string];
void prInd (int cnt) {
for (i = 0; i < cnt; i++) printf (" ");
}
}
BEG_G {
$tvtype = TV_prepostfwd;
$tvroot = node($,ARGV[0]);
}
N {
if (seen[$.name]) indent--;
else {
prInd(indent);
print ($.name);
seen[$.name] = 1;
indent++;
}
}
Prints the depth-first traversal of the graph, starting with the node whose name is ARGV[0], as an indented list. πΈ
πΏ ENVIRONMENT πΏ
GVPRPATHβ a colon-separated list of directories to be searched to find the file specified by the-foption.gvprhas a default list built in. IfGVPRPATHis not defined, the default list is used. IfGVPRPATHstarts with colon, the list is formed by appendingGVPRPATHto the default list. IfGVPRPATHends with colon, the list is formed by appending the default list toGVPRPATH. Otherwise,GVPRPATHis used for the list. β
On Windows systems, replace colon'' with semicolon'' in the previous paragraph. πͺ
π BUGS AND WARNINGS π
ok so before you go absolutely feral with this language, bestie, read this part. it's giving caution tape for a reason. π
π¨ the traversal one (this one is real)
If your script is out here deleting nodes while you're inside an N{} or E{} block β and you're using BFS or DFS traversals β be careful, okay? π Those traversals rely on stacks and queues of nodes, so the vibes get messy if you're mutating the graph mid-walk. Deleting nodes during BFS/DFS traversal is literally the "not me accidentally destabilizing my own iterator" moment. Be careful. π«Ά
π the shell-quoting one
When the program is given as a command line argument, the usual shell interpretation takes place, and that can absolutely mess with some of the special names in gvpr. β¨
To avoid this, it is best to wrap the program in single quotes. no cap.
πͺ€ the backslash trap
If your string constants contain pattern metacharacters and you want to escape them so you don't trigger pattern matching β you will probably need two backslashes, because a single backslash gets lost when the string is originally scanned. π
Usually it's simpler to just use strcmp and avoid pattern matching altogether. iykyk.
π¦ the graph library glow-up (24 April 2008)
As of 24 April 2008, gvpr switched to using a new, underlying graph library. The new model is simpler: there is only one copy of a node, not one copy for each subgraph logically containing it. slay, honestly.
But β and this is the important part β it means iterators such as nxtnode cannot traverse a subgraph using just a node argument. π
For this reason, subgraph traversal requires new functions ending in "_sg", which also take a subgraph argument. The versions without that suffix will always traverse the root graph. periodt.
πΈ the scope situation
There is a single global scope, except for formal function parameters β and even those can interfere with the type system. π Also, the extent of all variables is the entire life of the program.
It might be preferable for scope to reflect the natural nesting of the clauses, or for the program to at least reset locally declared variables. But for now?
It is advisable to use distinct names for all variables. π
π₯ the type-checking jumpscare
If a function ends with a complex statement β such as an IF statement β with each branch doing a return, type checking may fail. π«
Functions should use a return at the end. iconic behavior, just do it.
π§ the (char*)0 thing
The expr library does not support string values of (char*)0. Which means we can't distinguish between "" and (char*)0 edge keys. π
For the purposes of looking up and creating edges, we translate "" to be (char*)0, since this latter value is necessary in order to look up any edge with a matching head and tail.
Related to this: strings converted to integers act like char pointers, getting the value 0 or 1 depending on whether the string consists solely of zeroes or not. So:
((int)"2")
evaluates to 1. π yes really.
π the classic C lore
The language inherits the usual C problems, such as dangling references and the confusion between '=' and '=='. some things never change, bestie. π
π AUTHOR π
Emden R. Gansner <erg@research.att.com>
π SEE ALSO π
and that's the whole page, bestie!! π this was GVPR(1), source/version GVPR(1), dated 29 August 2013 β go forth and write the most unhinged graph-processing scripts of your life, you absolute main character. π¦β¨π
π¦ where this page comes from
- arch rolling: graphviz 16.1.0-2 Β· EPL
- fedora 43: graphviz 13.1.2-3.fc43 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- fedora 43: graphviz 13.1.2-3.fc43 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- fedora 44: graphviz 14.1.2-2.fc44 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- fedora 44: graphviz 14.1.2-2.fc44 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- fedora 44: graphviz 14.1.4-2.fc44 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- fedora 44: graphviz 14.1.4-2.fc44 Β· epl-1.0 AND cpl-1.0 AND bsd-3-clause AND mit AND gpl-3.0-or-later WITH bison-exception-2.2 AND apache-1.1 AND lgpl-2.0-or-later WITH libtool-exception AND smlnj AND hpnd-uc
- nixpkgs unstable: graphviz 15.1.1
- ubuntu resolute: graphviz 14.1.2-1ubuntu1 Β· EPL-1.0
- ubuntu stonking: graphviz 14.1.2-1ubuntu2 Β· EPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms