Skip to content

Commit 7f43e52

Browse files
committed
AST: fix casting from Decl to GenericContext
Fixes `cast<GenericContext>(someDecl)`. I don't know why this didn't show up as a crash so far. But slightly changing `Decl` results in a wrong type cast and a crash.
1 parent fadff00 commit 7f43e52

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

include/swift/AST/Decl.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1568,6 +1568,8 @@ class GenericContext : private _GenericContext, public DeclContext {
15681568
/// Retrieve the position of any where clause for this context's
15691569
/// generic parameters.
15701570
SourceRange getGenericTrailingWhereClauseSourceRange() const;
1571+
1572+
static bool classof(const Decl *D);
15711573
};
15721574
static_assert(sizeof(_GenericContext) + sizeof(DeclContext) ==
15731575
sizeof(GenericContext), "Please add fields to _GenericContext");
@@ -9589,6 +9591,16 @@ inline bool DeclContext::classof(const Decl *D) {
95899591
}
95909592
}
95919593

9594+
inline bool GenericContext::classof(const Decl *D) {
9595+
switch (D->getKind()) { //
9596+
default: return false;
9597+
#define DECL(ID, PARENT) // See previous line
9598+
#define GENERIC_DECL(ID, PARENT) \
9599+
case DeclKind::ID: return true;
9600+
#include "swift/AST/DeclNodes.def"
9601+
}
9602+
}
9603+
95929604
inline DeclContext *DeclContext::castDeclToDeclContext(const Decl *D) {
95939605
// XXX -- ModuleDecl is not defined in Decl.h, but because DeclContexts
95949606
// preface decls in memory, any DeclContext type will due.

include/swift/AST/DeclContext.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,20 @@ namespace llvm {
10131013
}
10141014
};
10151015

1016+
template<class FromTy>
1017+
struct CastInfo<::swift::GenericContext, FromTy, std::enable_if_t<is_simple_type<FromTy>::value>>
1018+
: public CastIsPossible<::swift::GenericContext, FromTy>,
1019+
public DefaultDoCastIfPossible<::swift::GenericContext *, FromTy,
1020+
CastInfo<::swift::GenericContext, FromTy>> {
1021+
static inline ::swift::GenericContext *castFailed() { return nullptr; }
1022+
1023+
static inline ::swift::GenericContext *doCast(const FromTy &val) {
1024+
auto *genCtxt = val->getAsGenericContext();
1025+
assert(genCtxt);
1026+
return const_cast<::swift::GenericContext *>(genCtxt);
1027+
}
1028+
};
1029+
10161030
template<class FromTy>
10171031
struct CastInfo<::swift::IterableDeclContext, FromTy, std::enable_if_t<is_simple_type<FromTy>::value>>
10181032
: public CastIsPossible<::swift::IterableDeclContext, FromTy>,

0 commit comments

Comments
 (0)