0

I am trying to find all division operators in a large c file. I saw this example for a Python Code.

And I tried to use it for my c file. So, I parsed my c file into ast using pycparser as follows:

from pycparser import parse_file, c_parser, c_generator

def translate_to_c(filename):
    ast = parse_file(filename, use_cpp=True)
    ast.show()
translate_to_c('source.c')

Then I tried using the example by modifying translate_to_c as follows:

def translate_to_c(filename):
    ast = parse_file(filename, use_cpp=True)
    ast.show()
    last_lineno = None
    for node in ast.walk(ast):
        # Not all nodes in the AST have line numbers, remember latest one
        if hasattr(node, "lineno"):
            last_lineno = node.lineno

        # If this is a division expression, then show the latest line number
        if isinstance(node, ast.Div):
            print(last_lineno)

I get the following error:

line 25, in translate_to_c
    for node in ast.walk(ast):
AttributeError: 'FileAST' object has no attribute 'walk'

So any ideas on how I can use this example in my code? or How to loop on the ast file in general ?

Nemo
  • 85
  • 2
  • 11

1 Answers1

2

Using Python's built-in ast library and pycparser is very different. One is a Python AST, the other parses C into C ASTs. They are different types from different libraries - you cannot expect one's methods (like walk) to just magically work for another!

I recommend you start with pycparser's examples: https://github.com/eliben/pycparser/tree/master/examples

For instance, this examples finds all function calls in C code. It should be easy to adjust to find all division operators. The explore_ast example shows you how to feel your way around an AST.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412