[cfe-dev] Type/offset/size of flexible array struct member

Jiri Olsa via cfe-dev cfe-dev at lists.llvm.org
Wed May 29 04:13:14 PDT 2019


hi,
I have a question on how to correctly identify flexible array
type in clang_visitChildren walk.

With following example struct:

struct a {
  int a;
  int b[];
};

the attached program prints CXType::kind, which correctly shows
CXType_IncompleteArray value, but size and offset values are -2.

$ ./ex
Clang error 0
field a, size 4, offset -2, kind: 17
field b, size -2, offset -2, kind: 114

Is that expected? Is it enough to check for CXType_IncompleteArray
value in CXType::kind for flexible array type?

thanks,
jirka


---
#include <clang-c/Index.h>
#include <iostream>
#include <vector>

using namespace std;

static std::string get_clang_string(CXString string)
{
	std::string str = clang_getCString(string);
	clang_disposeString(string);
	return str;
}

int main(int argc, char **argv)
{
	CXIndex index = clang_createIndex(1, 1);
	CXErrorCode error;
	CXTranslationUnit translation_unit;
	std::string input = "struct a { int a; int b[]; };";
	unsigned err;

	CXUnsavedFile unsaved_files[] = {
		{
			.Filename = "definitions.h",
			.Contents = input.c_str(),
			.Length = input.size(),
		},
	};

	error = clang_parseTranslationUnit2(
			index,
			"definitions.h",
			NULL, 0,
			unsaved_files, sizeof(unsaved_files)/sizeof(CXUnsavedFile),
			CXTranslationUnit_DetailedPreprocessingRecord,
			&translation_unit);

	cerr << "Clang error " << error << endl;

	CXCursor cursor = clang_getTranslationUnitCursor(translation_unit);

	err = clang_visitChildren(cursor,
        [](CXCursor c, CXCursor parent, CXClientData client_data)
        {
		if (clang_getCursorKind(c) == CXCursor_StructDecl)
			return CXChildVisit_Recurse;
			
		if (clang_getCursorKind(c) != CXCursor_FieldDecl)
			return CXChildVisit_Continue;

		auto ident = get_clang_string(clang_getCursorSpelling(c));
		auto type = clang_getCanonicalType(clang_getCursorType(c));
		auto offset = clang_Cursor_getOffsetOfField(c);

		cout << "field " << ident << ", size " << clang_Type_getSizeOf(type) << ", offset " << offset << ", kind: " << type.kind << endl;
		return CXChildVisit_Recurse;

        },
	NULL);

	return 0;
}



More information about the cfe-dev mailing list