3

I am struggling parsing cpp file with libclang and python.

Problem is that when I don't declare a class foo function is ignored by libclang while it is finding testString and main().

//test.cpp
std::string test1::foo(){

}

std::string *testString = "";

int main()
{
    return 0;
}

When I declare test1 class before function prototype as below it detects foo function.

//test.cpp
class test1{
    private:
    std::string foo();
};

std::string test1::foo(){

}

std::string *testString = "";

int main()
{
    return 0;
}

My humble parser script:

import sys
import clang.cindex
clang.cindex.Config.set_library_file('C:/Program Files/LLVM/bin/libclang.dll')
def list_nodes(node):
    for c in node.get_children():
        print("-------------------")
        print(c.spelling)
        print(c.access_specifier)
        print(c.type.kind)
        list_nodes(c)


index = clang.cindex.Index.create()
tu = index.parse("test.cpp")
list_nodes(tu.cursor)

Problem with my project is that I am using cmake and want to parse some of the cpp files and fetch information from them. Since my project relies on cmake most of the time header and source files are not on the same directory. I dont want to create a mess with binding these files on a different place. Is there any practice to get header locations automatically from cmake files. Or alternatively a way of parsing these functions and variables in just cpp files.

necilAlbayrak
  • 824
  • 6
  • 9

1 Answers1

0

What are you using as the backend tool for CMake? Just ordinary make ? If so, you can use make -n to get the list of commands to be executed; they'll contain the necessary -I /header/locations flags.

You can't really parse fragments of C++ code. Even humans have issues with that, so we want full compiling source code on StackOverflow. For instance, you are assuming that test1 is a class. But what if it's a union ? (Yes, a union can have methods). What's also missing from the definition is what type of method this is, virtual or not.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Thank you for your feedback.I am aware that cpp is a hard language to parse. I decided using antlr with cpp14 grammar. So far it works fine for me. – necilAlbayrak Oct 30 '18 at 07:56