Drawing cfg using antlr4, graphiz and python and parser is empty

69 Views Asked by At

I am using 2 files I will be sharing link if any doubt can visit one is cfg_from_stding.py and cfg_extractor_visitor.py and also I will share the lexer and go file go file is simple and correct. I think in Lexer file something needs to be corrected or added.

On printing I am getting parse tree as : [] which means empty

def get_parse_tree(input_stream):
    lexer = GoLexer(input_stream)
    stream = CommonTokenStream(lexer)

    # Print detailed information about lexed tokens
    print("Lexed Tokens:")
    for token in lexer.getAllTokens():
        print(f"Token: {token.type}, Text: '{token.text}', Line: {token.line}, Column: {token.column}")


    # Print lexed tokens
    print("Lexed Tokens:")
    for token in stream.tokens:
        print(token)

    parser = GoParser(stream)
    return parser.sourceFile()

def extract(input_stream):
    cfg_extractor = CFGExtractorVisitor()
    parse_tree = get_parse_tree(input_stream)
    print("Parse Tree:", parse_tree)  # Add this line to print the parse tree
    graph = cfg_extractor.extract(parse_tree)
    return graph

EDITS

def save_graphs(graphs, output_dir):
    import os
    import networkx as nx
    import matplotlib.pyplot as plt

    print(f"Total graphs to process: {len(graphs)}")

    for i, graph in enumerate(graphs):
        print(f"Processing graph {i}")
        try:
            output_path = os.path.join(output_dir, f"graph_{i}.png")
            nx.draw(graph, with_labels=True, font_weight='bold', node_color='skyblue')
            plt.show()  # Display the figure
            plt.savefig(output_path)
            plt.close()
            print(f"Graph {i} saved to {output_path}")
        except Exception as e:
            print(f"Error processing graph {i}: {e}")

    print(f"All graphs processed and saved to {output_dir}")


def draw_CFG(graph, output_path, verbose=False):
    if isinstance(graph, list):
        print("Error: Received a list of functions instead of a graph.")
        return

cfg_from_stdin.py

cfg_extractor_visitor.py

GoLexer.g4

test.go

1

There are 1 best solutions below

3
On

On printing I am getting parse tree as : [] which means empty

Not necessarily. What happens if you do this instead:

print("Parse Tree:", parse_tree.toStringTree(recog=parser))

EDIT

Also try to print the tree without messing around with the token stream to see if that prodcues the expected result:

input_stream = ...
lexer = GoLexer(input_stream)
parser = GoParser(CommonTokenStream(lexer))
parse_tree = parser.sourceFile()
print("Parse Tree:", parse_tree.toStringTree(recog=parser))

Otherwise, please update your question with enough code for others to reproduce the error (see: stackoverflow.com/help/minimal-reproducible-example).