check.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_CHECK_H_
  5. #define CARBON_COMMON_CHECK_H_
  6. #include "common/check_internal.h"
  7. namespace Carbon {
  8. // Checks the given condition, and if it's false, prints a stack, streams the
  9. // error message, then exits. This should be used for unexpected errors, such as
  10. // a bug in the application.
  11. //
  12. // For example:
  13. // CARBON_CHECK(is_valid, "Data is not valid!");
  14. //
  15. // The condition must be parenthesized if it contains top-level commas, for
  16. // example in a template argument list:
  17. // CARBON_CHECK((inst.IsOneOf<Call, TupleLiteral>()),
  18. // "Unexpected inst {0}", inst);
  19. #define CARBON_CHECK(condition, ...) \
  20. CARBON_INTERNAL_CHECK_CONDITION(condition) \
  21. ? (void)0 : CARBON_INTERNAL_CHECK(condition __VA_OPT__(, ) __VA_ARGS__)
  22. // DCHECK calls CHECK in debug mode, and does nothing otherwise.
  23. #ifndef NDEBUG
  24. #define CARBON_DCHECK(condition, ...) \
  25. CARBON_CHECK(condition __VA_OPT__(, ) __VA_ARGS__)
  26. #else
  27. // When in a debug build we want to preserve as much as we can of how the
  28. // parameters are used, other than making them be trivially in dead code and
  29. // eliminated by the optimizer. As a consequence we preserve the condition but
  30. // prefix it with a short-circuit operator, and we still emit the (dead) call to
  31. // the check implementation. But we use a special implementation that reduces
  32. // the compile time cost.
  33. #define CARBON_DCHECK(condition, ...) \
  34. (true || CARBON_INTERNAL_CHECK_CONDITION(condition)) \
  35. ? (void)0 \
  36. : CARBON_INTERNAL_DEAD_DCHECK(condition __VA_OPT__(, ) __VA_ARGS__)
  37. #endif
  38. // This is similar to CHECK, but is unconditional. Writing
  39. // `CARBON_FATAL("message")` is clearer than `CARBON_CHECK(false, "message")
  40. // because it avoids confusion about control flow.
  41. //
  42. // For example:
  43. // CARBON_FATAL("Unreachable!");
  44. #define CARBON_FATAL(...) CARBON_INTERNAL_FATAL(__VA_ARGS__)
  45. } // namespace Carbon
  46. #endif // CARBON_COMMON_CHECK_H_