parsingcompiler-constructionclang

Clang: ASTConsumer vs ASTVisitor


What is the difference between the ASTConsumer and RecursiveASTVisitor in Clang? When would someone need to use ASTConsumer?

Looking at all the tutorials online and documentation on clang, it looks like ASTConsumer is only used to call the RecursiveASTVisitor. It isn't clear why these two interfaces exist separately.


Solution

  • The main difference between these two interfaces is that RecursiveASTVisitor consumes the AST only after the translation unit has been parsed completely, whereas ASTConsumer gives you fine grained control over the parsing itself. The functions in ASTConsumer are called during parsing (like the function HandleTagDeclDefinition below):

      /// HandleTagDeclDefinition - This callback is invoked each time a TagDecl
      /// (e.g. struct, union, enum, class) is completed.  This allows the client to
      /// hack on the type, which can occur at any point in the file (because these
      /// can be defined in declspecs).
      virtual void HandleTagDeclDefinition(TagDecl *D) {}
    

    Generally for tools that operate on AST, the only use of an ASTConsumer is to call the RecursiveASTVisitor, but if you want to manipulate the construction of the AST depending on what you have already parsed, then you would use ASTConsumer.