Chris Kay | 5b78769 | 2021-07-19 16:57:32 +0100 | [diff] [blame^] | 1 | #[=======================================================================[.rst: |
| 2 | ArmAssert |
| 3 | --------- |
| 4 | |
| 5 | .. default-domain:: cmake |
| 6 | |
| 7 | .. command:: arm_assert |
| 8 | |
| 9 | Assert an invariant, and fail the build if the invariant is broken. |
| 10 | |
| 11 | .. code-block:: cmake |
| 12 | |
| 13 | arm_assert(CONDITION <condition> [MESSAGE <message>]) |
| 14 | |
| 15 | This function takes a condition ``<condition>`` in :ref:`Condition Syntax`, |
| 16 | evaluates it, and fails the build with the message ``<message>`` if evaluation |
| 17 | does not yield a truthy result. If no message is provided, the ``<condition>`` |
| 18 | is instead printed. |
| 19 | |
| 20 | .. code-block:: cmake |
| 21 | :caption: Example usage (with message) |
| 22 | :linenos: |
| 23 | |
| 24 | arm_assert( |
| 25 | CONDITION STACK GREATER_EQUAL 256 |
| 26 | MESSAGE "The stack must be at least 256 bytes.") |
| 27 | |
| 28 | # CMake Error at cmake/Modules/ArmAssert.cmake:42 (message): |
| 29 | # The stack must be at least 256 bytes. |
| 30 | # Call Stack (most recent call first): |
| 31 | # CMakeLists.txt:42 (arm_assert) |
| 32 | |
| 33 | # ... and is functionally identical to... |
| 34 | |
| 35 | if(NOT STACK GREATER_EQUAL 256) |
| 36 | message(FATAL_ERROR "The stack must be at least 256 bytes.") |
| 37 | endif() |
| 38 | |
| 39 | .. code-block:: cmake |
| 40 | :caption: Example usage (without message) |
| 41 | :linenos: |
| 42 | |
| 43 | arm_assert(CONDITION STACK GREATER_EQUAL 256) |
| 44 | |
| 45 | # CMake Error at cmake/Modules/ArmAssert.cmake:42 (message): |
| 46 | # An assertion was triggered: STACK GREATER_EQUAL 256 |
| 47 | # Call Stack (most recent call first): |
| 48 | # CMakeLists.txt:42 (arm_assert) |
| 49 | |
| 50 | # ... and is functionally identical to... |
| 51 | |
| 52 | if(NOT STACK GREATER_EQUAL 256) |
| 53 | message(FATAL_ERROR "An assertion was triggered: STACK GREATER_EQUAL 256") |
| 54 | endif() |
| 55 | #]=======================================================================] |
| 56 | |
| 57 | include_guard() |
| 58 | |
| 59 | function(arm_assert) |
| 60 | set(options "") |
| 61 | set(single-args "") |
| 62 | set(multi-args "CONDITION;MESSAGE") |
| 63 | |
| 64 | cmake_parse_arguments(PARSE_ARGV 0 ARG |
| 65 | "${options}" "${single-args}" "${multi-args}") |
| 66 | |
| 67 | if(NOT DEFINED ARG_MESSAGE) |
| 68 | set(ARG_MESSAGE "An assertion was triggered: " ${ARG_CONDITION}) |
| 69 | endif() |
| 70 | |
| 71 | string(REPLACE ";" "" ARG_MESSAGE "${ARG_MESSAGE}") |
| 72 | |
| 73 | if(NOT (${ARG_CONDITION})) |
| 74 | message(FATAL_ERROR "${ARG_MESSAGE}") |
| 75 | endif() |
| 76 | endfunction() |