Question

I am using libclang to parse a objective c source code file. The following code finds all Objective-C instance method declarations, but it also finds declarations in the includes:

 enum CXCursorKind curKind  = clang_getCursorKind(cursor);
 CXString curKindName  = clang_getCursorKindSpelling(curKind);

 const char *funcDecl="ObjCInstanceMethodDecl";

 if(strcmp(clang_getCString(curKindName),funcDecl)==0{


 }

How can I skip everything, which comes from header includes? I am only interested in my own Objective-C instance method declarations in the source file, not in any of the includes.

e.g. the following should not be included

...

Location: /System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:15:9:315
Type: 
TypeKind: Invalid
CursorKind: ObjCInstanceMethodDecl

...
Was it helpful?

Solution

Answering this question because I couldn't believe that hard-coding paths comparisons was the only solution, and indeed, there is a clang_Location_isFromMainFile function that does exactly what you want, so that you can filter unwanted results in the visitor, like this :

if (clang_Location_isFromMainFile (clang_getCursorLocation (cursor)) == 0) {
  return CXChildVisit_Continue;
}

OTHER TIPS

The only way I know would be to skip unwanted paths during the AST visit. You can for example put something like the following in your visitor function. Returning CXChildVisit_Continue avoids visiting the entire file.

CXFile file;
unsigned int line, column, offset;
CXString fileName;
char * canonicalPath = NULL;

clang_getExpansionLocation (clang_getCursorLocation (cursor),
                            &file, &line, &column, &offset);

fileName = clang_getFileName (file);
if (clang_getCString (fileName)) {
  canonicalPath = realpath (clang_getCString (fileName), NULL);
}
clang_disposeString (fileName);

if (strcmp(canonicalPath, "/canonical/path/to/your/source/file") != 0) {
  return CXChildVisit_Continue;
}

Also, why compare CursorKindSpelling instead of the CursorKind directly?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top