[cfe-dev] Iterating over AST node objects

David Rector via cfe-dev cfe-dev at lists.llvm.org
Fri Oct 30 17:30:03 PDT 2020


Yes those lines represent nodes.  You do not necessarily need ASTContext to look at a node’s descendants: you can just use the node’s methods.  

Were these sugar (= syntax-only) type nodes, you could iterate over the child of each successive node via `desugar()`, and successively desugar while searching for a Type subclass T via `getAs<T>()`.  

But pointee types/array element types are of course not sugar: they are distinct semantic entities, so desugar/getAs won’t will not pass through them.  Hence your problem.

Fortunately there seems to be a `getPointeeOrArrayElementType()` to help peel off the semantic layers you want to look through, analogous to `desugar()` — but unfortunately there is not a `getAs` analog for this case, so you have to write the search manually.  

Something like this should work (not tested):

```
PointerType *getInnermostPointerType(const Type *T) {
  const PointerType *res = nullptr;

  while (true) {
    const Type *pointeeOrElement = T->getPointeeOrArrayElementType();
    if (pointeeOrElement == T)
      // T is neither a pointer nor array type: we’re done.
      break;

    // T is a pointer or array type.
    if (isa<PointerType>(T)) 
      res = cast<PointerType>(T);
   
    // iterate T, keep looking
    T = pointeeOrElement;
  }
  return res;
}
```

> On Oct 30, 2020, at 2:12 PM, Pratyush Das via cfe-dev <cfe-dev at lists.llvm.org> wrote:
> 
> Hi,
> 
> If I dump() a clang::Type object, I can see this AST representation - 
> 
> ConstantArrayType 0x555562830ea0 'const char **const [0]' 0 
> `-QualType 0x555562830c81 'const char **const' const
>   `-PointerType 0x555562830c80 'const char **'
>     `-PointerType 0x5555627ed2a0 'const char *'
>       `-QualType 0x5555627ec7d1 'const char' const
>         `-BuiltinType 0x5555627ec7d0 'char'
> 
> Is there a way to use the ASTContext to iterate over each node? (Do each of those lines represent a node?)
> 
> My motivation is to get the inner most PointerType object.
> 
> Regards,
> 
> -- 
> Pratyush Das
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20201030/174d3f3e/attachment.html>


More information about the cfe-dev mailing list