Search code examples
c++clangabstract-syntax-treelibclang

Get operator type for CXCursor_BinaryOperator


I'm trying to find an assignment in C++ source file:

x = 10;

I'm using libclang to parse it and traverse AST. There is an CXCursor_BinaryOperator that represents binary operators. Is there a way to determine whether it is an assignment or any other binary operator (like + or <= or !=)? If not then how can I determine if the expression is an assignment or not?

Thnks in advance.


Solution

  • The following code may work for you:

      CXToken *tokens;
      unsigned numTokens;
      CXSourceRange range = clang_getCursorExtent(cursor);
      clang_tokenize(tu, range, &tokens, &numTokens);
      for(unsigned i=0; i<numTokens; i++) {
        CXString s = clang_getTokenSpelling(tu, tokens[i]);
        const char* str = clang_getCString(s);
        if( strcmp(str, "=") == 0 ) {
          /* found */
        }
        clang_disposeString(s);
      }
      clang_disposeTokens(tu, tokens, numTokens);