title: Clang Tool that extracts the lambda body given the lambda type
body: <p>I'm currently trying to implement a Clang Tool based on RecursiveASTVisitors (based on <a href="https://clang.llvm.org/docs/RAVFrontendAction.html" rel="nofollow noreferrer">this</a> tutorial) that applies code transformations based on lambdas given to a function.</p>
  
  <p>E.g. generate something based on the lambda given as an argument to <code>foo</code>:</p>
  
  <pre><code>foo([](){});
  </code></pre>
  
  <p>This is easily possible. Find all <code>callExpr</code>s that have the name <code>foo</code> and then find all <code>lambdaExpr</code>s that are descendants of this <code>callExpr</code>:</p>
  
  <pre><code>struct LambdaExprVisitor : public RecursiveASTVisitor&lt;LambdaExprVisitor&gt; {
    bool VisitLambdaExpr(LambdaExpr * lambdaExpr) {
      //Do stuff
      lambdaExpr-&gt;getCallOperator()-&gt;getBody()-&gt;dump();
      return true;
    }
  };
  
  struct CallVisitor : public RecursiveASTVisitor&lt;CallVisitor&gt; {
    //Find call expressions based on the given name
    bool VisitCallExpr(CallExpr * expr) {
      auto * callee = expr-&gt;getDirectCallee(); 
      if(callee != nullptr &amp;&amp; callee-&gt;getName() == "foo") {
        visitor.TraverseCallExpr(expr);
      }
      return true;
    }
    LambdaExprVisitor visitor;
  };
  </code></pre>
  
  <p>The problem that I now have is that there are multiple ways to get to pass a lambda function to this original function <code>foo</code>, e.g.:</p>
  
  <pre><code>auto bar() { return [](){}; }
  
  int main() {
    foo(bar());
  }
  </code></pre>
  
  <p>And the earlier approach to get the body does not work here.</p>
  
  <p>Now I thought that the lambdas' bodies are known during compile-time and therefore the lambda body must somehow be inferable given the value of the <code>Expr</code> of the given paramter:</p>
  
  <pre><code>struct CallVisitor : public RecursiveASTVisitor&lt;CallVisitor&gt; {
    bool VisitCallExpr(CallExpr * expr) {
      auto * callee = expr-&gt;getDirectCallee(); 
      if(callee != nullptr &amp;&amp; callee-&gt;getName() == "foo") {
        //Get the first argument which must be the lambda
        auto * arg = expr-&gt;getArg(0);
        //do something with the the first argument
        //?
      };
      return true;
    }
  };
  </code></pre>
  
  <p>Is there a way to get the lambda body at this point?
  If not, is there a way to infer the lambda body differently without having to resort to implementing all possible ways to pass a lambda body to <code>foo</code>? </p>
  
  <p>Note: A matcher-based solution would also work for me.</p>