Skip to content

Commit 3b67f16

Browse files
committed
fix error prone failure path in GetTypeFromScope
The earlier path forced a cast to TypeDecl, which will assert if that's not a valid cast, eg. if you have a NamespaceDecl. ``` llvm/include/llvm/Support/Casting.h:578: decltype(auto) llvm::cast(From*) [with To = clang::TypeDecl; From = clang::Decl]: Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' failed. ``` Allows for more flexible calls from cppyy, being less crash-prone. The old test has been extended.
1 parent ab4ca85 commit 3b67f16

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

lib/CppInterOp/CppInterOp.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1981,12 +1981,14 @@ TCppType_t GetTypeFromScope(TCppScope_t klass) {
19811981
return 0;
19821982

19831983
auto* D = (Decl*)klass;
1984-
ASTContext& C = getASTContext();
19851984

1986-
if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
1985+
if (auto* VD = dyn_cast<ValueDecl>(D))
19871986
return VD->getType().getAsOpaquePtr();
19881987

1989-
return C.getTypeDeclType(cast<TypeDecl>(D)).getAsOpaquePtr();
1988+
if (auto* TD = dyn_cast<TypeDecl>(D))
1989+
return getASTContext().getTypeDeclType(TD).getAsOpaquePtr();
1990+
1991+
return (TCppType_t) nullptr;
19901992
}
19911993

19921994
// Internal functions that are not needed outside the library are

unittests/CppInterOp/TypeReflectionTest.cpp

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -380,19 +380,23 @@ TYPED_TEST(CPPINTEROP_TEST_MODE, TypeReflection_GetComplexType) {
380380
}
381381

382382
TYPED_TEST(CPPINTEROP_TEST_MODE, TypeReflection_GetTypeFromScope) {
383-
std::vector<Decl *> Decls;
383+
std::vector<Decl*> Decls, SubDecls;
384384

385-
std::string code = R"(
385+
std::string code = R"(
386+
namespace N {
386387
class C {};
387388
struct S {};
388389
int a = 10;
390+
}
389391
)";
390392

391393
GetAllTopLevelDecls(code, Decls);
394+
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(Decls[0])), "NULL TYPE");
392395

393-
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(Decls[0])), "C");
394-
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(Decls[1])), "S");
395-
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(Decls[2])), "int");
396+
GetAllSubDecls(Decls[0], SubDecls);
397+
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(SubDecls[0])), "N::C");
398+
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(SubDecls[1])), "N::S");
399+
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(SubDecls[2])), "int");
396400
EXPECT_EQ(Cpp::GetTypeAsString(Cpp::GetTypeFromScope(nullptr)), "NULL TYPE");
397401
}
398402

0 commit comments

Comments
 (0)