Finding out if an assignment is within If statement's predicate

Hi All,

In my VisitBinaryOperator I want to treat assignments in IfStmt’s predicate check part differently
than the assignments in its body. For example:

if( (*ptrI = malloc(sizeof(int) * 10)) == NULL) // => this assignment is within predicate
msg = “success”; // assignment in body (treat it differently than the above)
else
msg = “fail”; // assignment in body

Here, I would like to handle the ptrI = malloc assignment differently than the other two assignments of ‘msg’. I tries setting a flag in VisitIfStmt, but that can’t distinguish between the two different kind of assignments.

Thanks!

Hi,

Have you tried setting a flag when visiting the conditional? E.g;

  void VisitIfStmt(const IfStmt *S) {
    InConditional = true;
    Visit(S->getCond());
    InConditional = false;
  }

vedant

Treating nodes of a single type differently depending on their specifics might be much easier with AST Matchers.

What you’re looking for is hasConditionVariableStatement [http://clang.llvm.org/docs/LibASTMatchersReference.html#hasConditionVariableStatement0Anchor].

Generally, try to use RecursiveASTVisitor when what you want is exactly node traversal, i.e. almost no dispatching. Otherwise, use AST Matchers. They’re easy to use and yet very powerful.

Hi Kirill,

I am not interested only in assignments within if condition, but just want to treat them differently. Specifically, I want to add a function/macro
after each assignment to an instance of a certain struct type.
Hence, I want an approach that can identify all the ‘=’ assignments to that type, and if they are within if conditions then use a function call to <function_for_if_assign>(… ) otherwise call <function_for_stmt_assign>(…).

Hi Kirill,

I am not interested only in assignments within if condition, but just want to treat them differently.

That was exactly my point…

Just see some clang-tidy checks for examples.