[clang] [C] Diagnose use of C++ keywords in C (PR #137234)
Aaron Ballman via cfe-commits
cfe-commits at lists.llvm.org
Tue Apr 29 04:54:39 PDT 2025
================
@@ -6107,6 +6109,44 @@ static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
SM.isInSystemMacro(D->getLocation());
}
+constexpr unsigned countCPlusPlusKeywords() {
+ unsigned Ret = 0;
+#define MODULES_KEYWORD(NAME)
+#define KEYWORD(NAME, FLAGS) ++Ret;
+#define CXX_KEYWORD_OPERATOR(NAME, TOK) ++Ret;
+#include "clang/Basic/TokenKinds.def"
+ return Ret;
+}
+
+static bool isKeywordInCPlusPlus(const Sema &S, const IdentifierInfo *II) {
+ if (!II)
+ return false;
+
+ // Build a static map of identifiers for all of the keywords in C++ that are
+ // not keywords in C. This allows us to do pointer comparisons instead of
+ // string comparisons when deciding whether the given identifier is a keyword
+ // or not. Note, this treats all keywords as being enabled, regardless of the
+ // setting of other language options. It intentionally disables the modules
+ // keywords because those are conditional keywords, so may be safe to use.
+ static auto Keywords = [&S] {
+ std::array<uintptr_t, countCPlusPlusKeywords()> Ret;
+ unsigned Idx = 0;
+#define MODULES_KEYWORD(NAME)
+#define KEYWORD(NAME, FLAGS) \
+ Ret[Idx++] = reinterpret_cast<uint64_t>( \
+ &S.getPreprocessor().getIdentifierTable().get(#NAME));
+#define CXX_KEYWORD_OPERATOR(NAME, TOK) \
+ Ret[Idx++] = reinterpret_cast<uint64_t>( \
+ &S.getPreprocessor().getIdentifierTable().get(#NAME));
+#include "clang/Basic/TokenKinds.def"
+ assert(Idx == Ret.size() && "expected to fill every member!");
+ llvm::sort(Ret);
+ return Ret;
+ }();
+
+ return llvm::binary_search(Keywords, reinterpret_cast<uintptr_t>(II));
----------------
AaronBallman wrote:
Good suggestion, I've gone ahead with those changes.
https://github.com/llvm/llvm-project/pull/137234
More information about the cfe-commits
mailing list