|
// https://godbolt.org/z/qEo1vGhqM |
|
// Use -std=c++23 -fcontracts -stdlib=libc++ |
|
// |
|
// Change the evaluation semantic using |
|
// -fcontract-evaluation-semantic=<ignore|observe|enforce|quick_enforce> |
|
// |
|
// Change evaluation in the standard library using: |
|
// -fcontract-group-evaluation-semantic=std=<...>@ |
|
// |
|
#include <string_view> |
|
#include <iostream> |
|
#include <contracts> |
|
|
|
int f(const int x) |
|
pre(x != 0) |
|
post(r : r != x) { |
|
return x + 1; |
|
} |
|
|
|
void try_contract_groups() { |
|
// Turn on all "mylib" assertions using. |
|
// -fcontract-group-evaluation-semantic=mylib=enforce |
|
// Disable the debug group with |
|
// -fcontract-group-evaluation-semantic=mylib=enforce,mylib.debug=ignore |
|
// Or change "mylib.other" to quick_enforce with |
|
// -fcontract-group-evaluation-semantic=mylib.hardening=quick_enforce |
|
// |
|
// Currently the flag is -fcontract-group-evaluation-semantic=mylib=observe |
|
contract_assert [[clang::contract_group("mylib")]] (true); |
|
contract_assert [[clang::contract_group("mylib.debug")]] (false && "mylib.debug"); |
|
contract_assert [[clang::contract_group("mylib.other")]] (false && "mylib.other"); |
|
} |
|
|
|
void stdlib_using_contracts() { |
|
std::cerr << "stdlib_using_contracts is about to quick_enforce and trap!" << std::endl; |
|
std::string_view sv; |
|
(void)sv.back(); |
|
} |
|
|
|
// Try overriding the violation handler |
|
void handle_contract_violation(std::contracts::contract_violation const& violation) { |
|
if (violation.semantic() == std::contracts::evaluation_semantic::observe) { |
|
std::cerr << violation.location().function_name() << ":" |
|
<< violation.location().line() |
|
<< ": observing violation my way: " |
|
<< violation.comment() |
|
<< std::endl; |
|
return; |
|
} |
|
std::contracts::invoke_default_contract_violation_handler(violation); |
|
} |
|
|
|
int main() { |
|
int r = f(1); |
|
try_contract_groups(); |
|
stdlib_using_contracts(); |
|
} |