|
| 1 | +# Import the graphviz library for creating and rendering graphs. |
| 2 | +import graphviz |
| 3 | + |
| 4 | +# Define the source code which represents a simple program. |
| 5 | +source = """ |
| 6 | +lire(a) # Read value for 'a' |
| 7 | +lire(b) # Read value for 'b' |
| 8 | +si a > b alors # If 'a' is greater than 'b' |
| 9 | + afficher("a est supérieur à b") # Print that 'a' is greater than 'b' |
| 10 | +sinon # Otherwise |
| 11 | + afficher("a n'est pas supérieur à b") # Print that 'a' is not greater than 'b' |
| 12 | +finsi # End of if-else statement |
| 13 | +""" |
| 14 | + |
| 15 | +# Function to create a control flow graph from the source code. |
| 16 | +def create_cfg_from_source(code): |
| 17 | + # Initialize the graph. |
| 18 | + dot = graphviz.Digraph(format='png') |
| 19 | + |
| 20 | + # Split the source code into lines and create nodes for each line. |
| 21 | + lines = code.strip().split('\n') |
| 22 | + nodes = {} |
| 23 | + |
| 24 | + for i, line in enumerate(lines): |
| 25 | + # Assign a unique node name for each line. |
| 26 | + node_name = chr(ord('A') + i) |
| 27 | + dot.node(node_name, line.strip()) |
| 28 | + nodes[i] = node_name |
| 29 | + |
| 30 | + # Connect nodes to represent the flow of control. |
| 31 | + dot.edge(nodes[0], nodes[1], label='Read b') # Connect 'lire(a)' to 'lire(b)' |
| 32 | + dot.edge(nodes[1], 'C', label='Evaluate') # Connect 'lire(b)' to 'si a > b alors' |
| 33 | + |
| 34 | + # Connect the decision node 'C' to its outcomes. |
| 35 | + dot.edge('C', nodes[4], label='False') # Connect 'si a > b alors' to 'a n'est pas supérieur à b' |
| 36 | + dot.edge('C', nodes[3], label='True') # Connect 'si a > b alors' to 'a est supérieur à b' |
| 37 | + |
| 38 | + # Connect the end of the false condition to the 'finsi' (end of if-else). |
| 39 | + dot.edge(nodes[4], nodes[5], label='Do') |
| 40 | + dot.edge(nodes[5], nodes[6], label='End') |
| 41 | + |
| 42 | + return dot, nodes |
| 43 | + |
| 44 | +# Function to render and save the control flow graph. |
| 45 | +def render_and_save(dot, filename): |
| 46 | + dot.render(filename, view=True) |
| 47 | + |
| 48 | +# Function to generate and save the control flow graph for the program. |
| 49 | +def control_flow_graph_for_program(code): |
| 50 | + dot, nodes = create_cfg_from_source(code) |
| 51 | + render_and_save(dot, 'control_flow_graph_comparison_program') |
| 52 | + |
| 53 | +# Generate and save the control flow graph for the provided source code. |
| 54 | +control_flow_graph_for_program(source) |
0 commit comments