7.4.2. Class Graph¶
Objects of class Graph wrap RFGs (resource flow graphs). A Graph object
allows operations on the common state of the RFG. You can load and save RFGs.
You can add, rename, and delete views of the RFG. You can get lists of all valid
attributes, node types, and edge types. You can access and change the values of graph
attributes. Additionally, you can get a set of all nodes or edges within a view of the
RFG matching a predicate.
7.4.2.1. Obtaining a Graph¶
class Graph([filename][, buffer])
Calling the constructor of the Graph class without parameters creates a new, empty RFG with a schema for C/C++. A single parameter is interpreted as a filename, provided as a string or path-like object. The file must exist and contain a valid RFG. If only the keyword parameter buffer is given, the RFG is read from these bytes, e.g., from the result of save_buffer. Listing Loading, creating, and saving an RFG shows how to obtain an RFG.
#!/usr/bin/env rfgscript
import sys
from bauhaus import rfg
# loads the RFG file given as first command line parameter
my_rfg = rfg.Graph(sys.argv[1])
# creates a new, empty graph
some_rfg = rfg.Graph()
# saves the new graph
# name is the second command line parameter
some_rfg.save(sys.argv[2])
Note
Scripts running in Gravis can also obtain the currently loaded RFG via the
Gravis scripting interface gravis.get_graph().
See Section The RFG Displayed in Gravis
7.4.2.2. Saving a Graph¶
save([filename])
The instance method save saves the graph to a file. If the filename already exists, it is silently overwritten. If the filename is not writable or otherwise invalid, an exception is raised describing why the operation failed. If the RFG was loaded from a file or a filename was set with set_filename, then the filename is known and can be omitted. Otherwise, omitting the filename raises NameError.
The instance method save_buffer returns the graph as bytes instead of writing it
to a file. set_filename sets the filename used by save when called without a
parameter, and get_filename returns it (or None if no filename is known).
7.4.2.3. Destroying a Graph¶
destroy()
If you no longer need an RFG, you can remove it by using the instance method destroy. RFGs are not automatically garbage collected.
Imagine you have to handle multiple RFGs, one after another. You could do it as shown in Listing Destroying an RFG.
from bauhaus import rfg
list_of_filenames = [...]
for filename in list_of_filenames:
r = rfg.Graph(filename)
#...process r...
r.save(filename+".result")
r.destroy()
A graph can also be used in a with statement, which calls destroy when the
block is exited; see Listing Destroying an RFG at the end of a with statement.
from bauhaus import rfg
list_of_filenames = [...]
for filename in list_of_filenames:
with rfg.Graph(filename) as r:
#...process r...
r.save(filename+".result")
7.4.2.4. General Operations¶
The two instance methods __eq__ and __ne__ check for equality and inequality, respectively, of two graphs.
Typically, both functions are called using the == and != operators;
see Listing Equality check.
Graph objects are equal in the sense of these operators if they have been created by the same constructor call. No logical check for graph isomorphism is performed.
from bauhaus import rfg
filename = "project.rfg"
rfg1 = rfg.Graph(filename)
rfg2 = rfg.Graph(filename)
rfg3 = rfg1
if rfg1 == rfg2:
print("Cannot happen because rfg1 and rfg2 have")
print("not been loaded by the same constructor call")
elif rfg1 == rfg3:
print("That's ok, rfg1 and rfg3 are equivalent accesses")
print("to the same object")
7.4.2.5. Node and Edge Types¶
Nodes and edges of the RFG are typed. These types are useful for matching purposes. The following operations are related to types:
The method node_type_names returns a list of all node types (as strings). You can check whether a string represents a node type by calling is_node_type_name. A string can be translated into a node type by node_type. If you need a new node type, use create_node_type and supply a name for the new type (which must not already be used as the name of a node type) and an optional parent type (identified by its type descriptor or its name). The method destroy_node_type removes a node type from the schema. It raises the TypeHasInstance exception if there are still nodes of the node type to be removed. It raises TypeHasSubtype if there are still node types referring to this type.
The method reparent_node_type changes the parent type of a node type. It raises InvalidNodeType if the new parent type is the node type itself or one of its subtypes, as this would introduce a cycle in the inheritance hierarchy.
A list of all node and edge types related to source code representation can be found in
Language Schema. You may also use Gravis to obtain
an overview of existing node and edge types: after loading an RFG file, the
Node types and Edge types
palette windows show tree views of all possible node and edge types along with their
icons and colors.
The same operations as for node types are permitted for edge types as well. reparent_edge_type raises InvalidEdgeType if it would introduce a cycle.
7.4.2.6. New Elements¶
The node and edge instance methods create a new node or edge of type descr. You can pass either a type descriptor or the type name as a string. The new element is not yet contained in any view of the graph, although it is already part of the graph. It must be inserted into a view using the add method of the View class.
7.4.2.7. Attributes of Graphs, Views, Nodes, and Edges¶
For a full, in-depth explanation of attribute handling, see Section Attributes.
Schema Handling for Attributes¶
The following set of operations can be used for manipulating the schema information about attributes:
Method graph_attribute_names returns a list of all graph attribute names (as strings).
The method graph_attribute converts a string into an attribute descriptor.
Whether a string denotes a valid graph attribute can be checked using the method is_graph_attribute_name.
A new graph attribute can be created using create_graph_attribute. The second parameter specifies the type of the values to be stored.
An attribute can be renamed using rename_graph_attribute.
If an attribute is no longer needed, it can be removed from the graph using destroy_graph_attribute.
The other methods work analogously for view, node, and edge attributes. The topic “attributes” is covered in detail in Section Attributes.
Value Handling for Attributes¶
For a full and in-depth explanation of attribute handling, see Section Attributes.
has_key checks whether the attribute key is set.
__getitem__ retrieves the stored value for attribute key.
__setitem__ sets a new value for the attribute.
__delitem__ removes an attribute value.
__iter__ iterates over the set attributes as pairs of name and value, e.g., in a
for loop over the graph.
keys returns a list of the names of all set attributes.
items returns a list of all set key-value pairs (where keys are strings).
get_string_list interprets the string attribute as a list and returns it.
set_string_list stores the given string list as a string.
append_to_string_list appends the given string to the string list stored in the attribute.
7.4.2.8. Membership in the Graph¶
__contains__(element)
The instance method __contains__ checks whether the element passed as a parameter (a view, a node, or an edge) is contained in the graph, or whether the attribute is set in the graph. The attribute can be specified either by a graph attribute descriptor or by a string denoting the name of the graph attribute.
The instance method __contains__ is also usable with the in operator.
Caution
__contains__ simply returns False instead of raising an exception in case an
attribute specified by name is not a valid graph attribute.
7.4.2.9. Access to Views¶
A view is a subgraph of an RFG.
The instance method view_names returns a list of names of all views in the graph (see Listing Printing the view names of an RFG). The instance method views returns a list of all views. If only the name of a view is known, the view can be accessed by passing the name to view. If no view with that name exists, view creates a new, empty view. Whether a view with a given name exists can be checked using is_view_name.
graph = rfg.Graph("...")
for view_name in graph.view_names():
print(view_name)
These instance methods return all elements (nodes or edges, respectively) in the view as
a set, or all elements of the graph if no view is given. If a matcher
function that takes a Node (or Edge) is supplied, only those elements
for which the matcher holds are returned;
see Listing Get the routine nodes contained in a view.
Note
Since nodes and edges return a full set of elements, it is recommended to use xnodes and xedges during iteration for memory management reasons.
from bauhaus import rfg
my_graph = rfg.Graph(filename)
my_view = my_graph.view(rfg.code_facts_view_name())
routine_type = my_graph.node_type("Routine")
def only_routines(node):
return node.is_of_subtype(routine_type)
all_routines_in_view = my_graph.nodes(my_view, only_routines)
7.4.2.10. Iterating the Elements Contained in a Graph¶
The instance methods xviews, xnodes, and xedges return generators for all views, nodes, and edges contained in the graph. If a view is passed, xnodes and xedges only yield the elements contained within that view.
The example in Listing Print the names of all views of an RFG prints the names of all views contained in an RFG.
from bauhaus import rfg
my_graph = rfg.Graph(filename)
for v in my_graph.xviews():
print(v.name())
If a matcher function that takes a Node (or Edge) is supplied,
only those elements for which the matcher holds are returned. Since the first parameter is
the view, the matcher function should be passed as a keyword parameter, or None
should be passed as the view.