From fd2e0483de089fb1459bf440d74e5b4e648a429f Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Fri, 22 Nov 2024 05:01:49 +0800 Subject: [PATCH] [clang-tidy] ignore consteval function in `ExceptionAnalyzer` (#116643) `ExceptionAnalyzer` can ignore `consteval` function even if it will throw exception. `consteval` function must produce compile-time constant. But throw statement cannot appear in constant evaluation. Fixed: #104457. --- .../clang-tidy/utils/ExceptionAnalyzer.cpp | 6 ++++++ clang-tools-extra/docs/ReleaseNotes.rst | 4 ++++ .../bugprone/exception-escape-consteval.cpp | 14 ++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-consteval.cpp diff --git a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp index 68f3ecf6bdaa..0fea7946a59f 100644 --- a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp +++ b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp @@ -320,6 +320,12 @@ bool isQualificationConvertiblePointer(QualType From, QualType To, } // namespace static bool canThrow(const FunctionDecl *Func) { + // consteval specifies that every call to the function must produce a + // compile-time constant, which cannot evaluate a throw expression without + // producing a compilation error. + if (Func->isConsteval()) + return false; + const auto *FunProto = Func->getType()->getAs(); if (!FunProto) return true; diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index f967dfabd1c9..dcfe68e020fc 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -162,6 +162,10 @@ Changes in existing checks ` check to treat `std::span` as a handle class. +- Improved :doc:`bugprone-exception-escape + ` by fixing false positives + when a consteval function with throw statements. + - Improved :doc:`bugprone-forwarding-reference-overload ` check by fixing a crash when determining if an ``enable_if[_t]`` was found. diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-consteval.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-consteval.cpp new file mode 100644 index 000000000000..6e4298bba8bf --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape-consteval.cpp @@ -0,0 +1,14 @@ +// RUN: %check_clang_tidy -std=c++20 %s bugprone-exception-escape %t -- \ +// RUN: -- -fexceptions -Wno-everything + +namespace GH104457 { + +consteval int consteval_fn(int a) { + if (a == 0) + throw 1; + return a; +} + +int test() noexcept { return consteval_fn(1); } + +} // namespace GH104457