Issue 241101
Summary Can't reliably distinguish typedef from struct tag
Labels new issue
Assignees
Reporter slburson
    I am using libclang in an FFI generator for Common Lisp.  It generates C or C++ adapter functions that call a function or method in the wrapped library.  Those functions use types in the library for their parameter and return types.  So it has to emit type names for those types.

Consider these two cases (I'm using `struct` here, but the same considerations apply to `class`, `union`, and `enum`):

```
struct foo { ... };

typedef struct { ... } bar;
```

References to `foo` must always be written `struct foo` in C; it is desirable to write them that way in C++, even though it's usually not necessary, because of the possibility that a function or variable named `foo` will also be in scope.  Of course, references to `bar` must never have the `struct` keyword.

The problem is that libclang papers over the distinction, to the point that figuring out what case one is looking at is nontrivial.  For instance, `clang_Cursor_isAnonymous`  does this in the `TagDecl` case:

```
 return TD->getTypedefNameForAnonDecl() == nullptr &&
 TD->getIdentifier() == nullptr;
```

I tried calling `clang_getFullyQualifiedName` on the type, with a printing policy in which `SuppressTagKeyword` is turned off.  This apparently should return a type name starting with "struct ", which I could check for.  Alas, it doesn't work for C++ unless the struct decl is in the global namespace.

So I wound up examining the USR.  According to Claude, anyway, the USR for an untagged type will match `"@[SUE]A@[^@]*$"`.  This is, of course, not a great solution since the USR is not a public interface.

I suggest adding a new API call such as this:

```
/**
 * Determine whether the given cursor represents a tagged
 * record declaration.
 */
unsigned clang_Cursor_isTaggedRecord(CXCursor C) {
  if (!clang_isDeclaration(C.kind))
    return 0;
  const Decl *D = cxcursor::getCursorDecl(C);
  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(D)) {
    return TD->getIdentifier() != nullptr;
 }

  return 0;
}
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to