Rework `constexpr` handling for C++ contracts.
Improves how C++ contract violations are diagnosed during constant evaluation.
This commit refactors how C++ contracts are handled during constexpr evaluation. Instead of always diagnosing contract violations at the outermost constant expression level, diagnostics now occur during evaluation if active. This change ensures that diagnostics have better context, stop evaluation at the point of violation if terminating, and correctly handle situations where an assertion failure occurs within an otherwise constant initialization. It also improves diagnostic reporting by using the predicate’s location and providing clearer explanations.
In Details
In gcc/cp/constexpr.cc, this patch modifies cxx_eval_constant_expression to diagnose contract violations when actively diagnosing, rather than unconditionally in cxx_eval_outermost_constant_expr. Contract diagnostics now receive cx_call_context and can terminate evaluation. If evaluation is not terminating but a violation is detected, it re-evaluates to get the diagnostic in context, addressing issues like PR c++/119497 and the handling of non-constant initializations with assertions ([expr.const.init]/4.1). check_for_failed_contracts is updated to use predicate locations and better…
- constexpr
- A C++ keyword indicating that a variable or function can be evaluated at compile time. This allows for computations to be performed during compilation rather than at runtime, potentially improving performance and enabling compile-time checks.
- contracts
- A C++20 feature (and further developed in later standards) that allows programmers to specify preconditions, postconditions, and assertions for functions and code blocks. These help in verifying program correctness and documenting expected behavior.
- constant evaluation
- The process by which the compiler determines the value of an expression at compile time, typically for
constexprorconstvariables. This requires all subexpressions to also be evaluable at compile time. - diagnostics
- Messages issued by the compiler to report errors, warnings, or informational notes about the source code. These help developers identify and fix problems.
- cx_call_context
- Contextual information related to a function call during C++ compilation. This likely includes details like the call site location, arguments, and relevant compile-time state, used for diagnostics and analysis.