clanglibtooling

When will a Clang AST node have multiple parents?


The class clang::ASTContext has a method:

DynTypedNodeList getParents(const NodeT &Node)

which returns a list of parent nodes of a given AST node.

Commonly AST as a tree will be a tree structure, but for some reasons (perhaps performance reasons) Clang allows a node have multiple parents.

Under what conditions (what C++ source code pattern), getParents() will return more than one parents?


Solution

  • Original answer (incorrect)

    AST is a tree, and each node has exactly one parent. getParents, though, returns not only a parent, but a parent of a parent and so on. So, in fact, the function should be better named something like getAncestors.

    Updated answer

    The original answer is indeed incorrect and getParents returns exactly one node for the vast majority of AST nodes. Here is a comment from clang-tidy that covers the topic:

    The case that a Stmt has multiple parents is rare but does actually occur in the parts of the AST that we're interested in. Specifically, InitListExpr nodes cause ASTContext::getParent() to return multiple parents for certain nodes in their subtree because RecursiveASTVisitor visits both the syntactic and semantic forms of InitListExpr, and the parent-child relationships are different between the two forms.

    Maybe there are other nodes as well, but I couldn't find information on that.