c++c++11clangoclint

How can I compare two source locations in clang?


this seems to be more a C++ problem rather than a Clang problem...

I have to use C++ in order to write an OCLint (static code analyzer) rule.

I wish to compare two objects from the Clang library that have the type "SourceLocation".

This type provides informations about the location (basically line & column) of an object (statement, declaration etc.) in the code.

Basically, I would like to know if the statement A begins and ends before, or after a statement B.

In pseudo-code, that means I would like to get a boolean from :

( stmt_A->getLocBegin() < stmt_B->getLocBegin() ), for example. Of course, this does not compile because the "<" operator is not defined between two objects of type "SourceLocation".

I found a method in the Clang documentation, but, as I am no frequent user of C++, I don't find a way to use it, here is this method :

http://clang.llvm.org/doxygen/classclang_1_1BeforeThanCompare_3_01SourceLocation_01_4.html

clang::BeforeThanCompare<SourceLocation>::BeforeThanCompare (SourceManager &SM)


bool clang::BeforeThanCompare< SourceLocation >::operator()(SourceLocation LHS, SourceLocation RHS)  const [inline]

I do not know how to use SourceManager, or simply how to get this boolean above.


Solution

  • Here is the final code that shows how to use SourceManager in Clang library, and how to compare two SourceLocation :

    // Declaration of a SourceManager
    SourceManager & loc_SM = _carrier->getSourceManager();
    
    // Declaration of an object BeforeThanCompare<SourceLocation>
    BeforeThanCompare<SourceLocation> isBefore(loc_SM); SourceLocation stmt_A, stmt_B;
    
    // Get whether stmt_A is before or after Stmt_B 
    bool A_before_B = isBefore(stmt_A,stmt_B);