Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Help / command / cmake_language.rst
1 cmake_language
2 --------------
3
4 .. versionadded:: 3.18
5
6 Call meta-operations on CMake commands.
7
8 Synopsis
9 ^^^^^^^^
10
11 .. parsed-literal::
12
13   cmake_language(`CALL`_ <command> [<arg>...])
14   cmake_language(`EVAL`_ CODE <code>...)
15   cmake_language(`DEFER`_ <options>... CALL <command> [<arg>...])
16   cmake_language(`SET_DEPENDENCY_PROVIDER`_ <command> SUPPORTED_METHODS <methods>...)
17   cmake_language(`GET_MESSAGE_LOG_LEVEL`_ <out-var>)
18
19 Introduction
20 ^^^^^^^^^^^^
21
22 This command will call meta-operations on built-in CMake commands or
23 those created via the :command:`macro` or :command:`function` commands.
24
25 ``cmake_language`` does not introduce a new variable or policy scope.
26
27 Calling Commands
28 ^^^^^^^^^^^^^^^^
29
30 .. _CALL:
31
32 .. code-block:: cmake
33
34   cmake_language(CALL <command> [<arg>...])
35
36 Calls the named ``<command>`` with the given arguments (if any).
37 For example, the code:
38
39 .. code-block:: cmake
40
41   set(message_command "message")
42   cmake_language(CALL ${message_command} STATUS "Hello World!")
43
44 is equivalent to
45
46 .. code-block:: cmake
47
48   message(STATUS "Hello World!")
49
50 .. note::
51   To ensure consistency of the code, the following commands are not allowed:
52
53   * ``if`` / ``elseif`` / ``else`` / ``endif``
54   * ``block`` / ``endblock``
55   * ``while`` / ``endwhile``
56   * ``foreach`` / ``endforeach``
57   * ``function`` / ``endfunction``
58   * ``macro`` / ``endmacro``
59
60 Evaluating Code
61 ^^^^^^^^^^^^^^^
62
63 .. _EVAL:
64
65 .. code-block:: cmake
66
67   cmake_language(EVAL CODE <code>...)
68
69 Evaluates the ``<code>...`` as CMake code.
70
71 For example, the code:
72
73 .. code-block:: cmake
74
75   set(A TRUE)
76   set(B TRUE)
77   set(C TRUE)
78   set(condition "(A AND B) OR C")
79
80   cmake_language(EVAL CODE "
81     if (${condition})
82       message(STATUS TRUE)
83     else()
84       message(STATUS FALSE)
85     endif()"
86   )
87
88 is equivalent to
89
90 .. code-block:: cmake
91
92   set(A TRUE)
93   set(B TRUE)
94   set(C TRUE)
95   set(condition "(A AND B) OR C")
96
97   file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
98     if (${condition})
99       message(STATUS TRUE)
100     else()
101       message(STATUS FALSE)
102     endif()"
103   )
104
105   include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)
106
107 Deferring Calls
108 ^^^^^^^^^^^^^^^
109
110 .. versionadded:: 3.19
111
112 .. _DEFER:
113
114 .. code-block:: cmake
115
116   cmake_language(DEFER <options>... CALL <command> [<arg>...])
117
118 Schedules a call to the named ``<command>`` with the given arguments (if any)
119 to occur at a later time.  By default, deferred calls are executed as if
120 written at the end of the current directory's ``CMakeLists.txt`` file,
121 except that they run even after a :command:`return` call.  Variable
122 references in arguments are evaluated at the time the deferred call is
123 executed.
124
125 The options are:
126
127 ``DIRECTORY <dir>``
128   Schedule the call for the end of the given directory instead of the
129   current directory.  The ``<dir>`` may reference either a source
130   directory or its corresponding binary directory.  Relative paths are
131   treated as relative to the current source directory.
132
133   The given directory must be known to CMake, being either the top-level
134   directory or one added by :command:`add_subdirectory`.  Furthermore,
135   the given directory must not yet be finished processing.  This means
136   it can be the current directory or one of its ancestors.
137
138 ``ID <id>``
139   Specify an identification for the deferred call.
140   The ``<id>`` may not be empty and may not begin with a capital letter ``A-Z``.
141   The ``<id>`` may begin with an underscore (``_``) only if it was generated
142   automatically by an earlier call that used ``ID_VAR`` to get the id.
143
144 ``ID_VAR <var>``
145   Specify a variable in which to store the identification for the
146   deferred call.  If ``ID <id>`` is not given, a new identification
147   will be generated and the generated id will start with an underscore (``_``).
148
149 The currently scheduled list of deferred calls may be retrieved:
150
151 .. code-block:: cmake
152
153   cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)
154
155 This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
156 Lists>` of deferred call ids.  The ids are for the directory scope in which
157 the calls have been deferred to (i.e. where they will be executed), which can
158 be different to the scope in which they were created.  The ``DIRECTORY``
159 option can be used to specify the scope for which to retrieve the call ids.
160 If that option is not given, the call ids for the current directory scope will
161 be returned.
162
163 Details of a specific call may be retrieved from its id:
164
165 .. code-block:: cmake
166
167   cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)
168
169 This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
170 Lists>` in which the first element is the name of the command to be
171 called, and the remaining elements are its unevaluated arguments (any
172 contained ``;`` characters are included literally and cannot be distinguished
173 from multiple arguments).  If multiple calls are scheduled with the same id,
174 this retrieves the first one.  If no call is scheduled with the given id in
175 the specified ``DIRECTORY`` scope (or the current directory scope if no
176 ``DIRECTORY`` option is given), this stores an empty string in the variable.
177
178 Deferred calls may be canceled by their id:
179
180 .. code-block:: cmake
181
182   cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)
183
184 This cancels all deferred calls matching any of the given ids in the specified
185 ``DIRECTORY`` scope (or the current directory scope if no ``DIRECTORY`` option
186 is given).  Unknown ids are silently ignored.
187
188 Deferred Call Examples
189 """"""""""""""""""""""
190
191 For example, the code:
192
193 .. code-block:: cmake
194
195   cmake_language(DEFER CALL message "${deferred_message}")
196   cmake_language(DEFER ID_VAR id CALL message "Canceled Message")
197   cmake_language(DEFER CANCEL_CALL ${id})
198   message("Immediate Message")
199   set(deferred_message "Deferred Message")
200
201 prints::
202
203   Immediate Message
204   Deferred Message
205
206 The ``Cancelled Message`` is never printed because its command is
207 canceled.  The ``deferred_message`` variable reference is not evaluated
208 until the call site, so it can be set after the deferred call is scheduled.
209
210 In order to evaluate variable references immediately when scheduling a
211 deferred call, wrap it using ``cmake_language(EVAL)``.  However, note that
212 arguments will be re-evaluated in the deferred call, though that can be
213 avoided by using bracket arguments.  For example:
214
215 .. code-block:: cmake
216
217   set(deferred_message "Deferred Message 1")
218   set(re_evaluated [[${deferred_message}]])
219   cmake_language(EVAL CODE "
220     cmake_language(DEFER CALL message [[${deferred_message}]])
221     cmake_language(DEFER CALL message \"${re_evaluated}\")
222   ")
223   message("Immediate Message")
224   set(deferred_message "Deferred Message 2")
225
226 also prints::
227
228   Immediate Message
229   Deferred Message 1
230   Deferred Message 2
231
232
233 .. _SET_DEPENDENCY_PROVIDER:
234 .. _dependency_providers:
235
236 Dependency Providers
237 ^^^^^^^^^^^^^^^^^^^^
238
239 .. versionadded:: 3.24
240
241 .. note:: A high-level introduction to this feature can be found in the
242           :ref:`Using Dependencies Guide <dependency_providers_overview>`.
243
244 .. code-block:: cmake
245
246   cmake_language(SET_DEPENDENCY_PROVIDER <command>
247                  SUPPORTED_METHODS <methods>...)
248
249 When a call is made to :command:`find_package` or
250 :command:`FetchContent_MakeAvailable`, the call may be forwarded to a
251 dependency provider which then has the opportunity to fulfill the request.
252 If the request is for one of the ``<methods>`` specified when the provider
253 was set, CMake calls the provider's ``<command>`` with a set of
254 method-specific arguments.  If the provider does not fulfill the request,
255 or if the provider doesn't support the request's method, or no provider
256 is set, the built-in :command:`find_package` or
257 :command:`FetchContent_MakeAvailable` implementation is used to fulfill
258 the request in the usual way.
259
260 One or more of the following values can be specified for the ``<methods>``
261 when setting the provider:
262
263 ``FIND_PACKAGE``
264   The provider command accepts :command:`find_package` requests.
265
266 ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
267   The provider command accepts :command:`FetchContent_MakeAvailable`
268   requests.  It expects each dependency to be fed to the provider command
269   one at a time, not the whole list in one go.
270
271 Only one provider can be set at any point in time.  If a provider is already
272 set when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called, the new
273 provider replaces the previously set one.  The specified ``<command>`` must
274 already exist when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called.
275 As a special case, providing an empty string for the ``<command>`` and no
276 ``<methods>`` will discard any previously set provider.
277
278 The dependency provider can only be set while processing one of the files
279 specified by the :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable.
280 Thus, dependency providers can only be set as part of the first call to
281 :command:`project`.  Calling ``cmake_language(SET_DEPENDENCY_PROVIDER)``
282 outside of that context will result in an error.
283
284 .. note::
285   The choice of dependency provider should always be under the user's control.
286   As a convenience, a project may choose to provide a file that users can
287   list in their :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable, but
288   the use of such a file should always be the user's choice.
289
290 Provider commands
291 """""""""""""""""
292
293 Providers define a single ``<command>`` to accept requests.  The name of
294 the command should be specific to that provider, not something overly
295 generic that another provider might also use.  This enables users to compose
296 different providers in their own custom provider.  The recommended form is
297 ``xxx_provide_dependency()``, where ``xxx`` is the provider-specific part
298 (e.g. ``vcpkg_provide_dependency()``, ``conan_provide_dependency()``,
299 ``ourcompany_provide_dependency()``, and so on).
300
301 .. code-block:: cmake
302
303   xxx_provide_dependency(<method> [<method-specific-args>...])
304
305 Because some methods expect certain variables to be set in the calling scope,
306 the provider command should typically be implemented as a macro rather than a
307 function.  This ensures it does not introduce a new variable scope.
308
309 The arguments CMake passes to the dependency provider depend on the type of
310 request.  The first argument is always the method, and it will only ever
311 be one of the ``<methods>`` that was specified when setting the provider.
312
313 ``FIND_PACKAGE``
314   The ``<method-specific-args>`` will be everything passed to the
315   :command:`find_package` call that requested the dependency.  The first of
316   these ``<method-specific-args>`` will therefore always be the name of the
317   dependency.  Dependency names are case-sensitive for this method because
318   :command:`find_package` treats them case-sensitively too.
319
320   If the provider command fulfills the request, it must set the same variable
321   that :command:`find_package` expects to be set.  For a dependency named
322   ``depName``, the provider must set ``depName_FOUND`` to true if it fulfilled
323   the request.  If the provider returns without setting this variable, CMake
324   will assume the request was not fulfilled and will fall back to the
325   built-in implementation.
326
327   If the provider needs to call the built-in :command:`find_package`
328   implementation as part of its processing, it can do so by including the
329   ``BYPASS_PROVIDER`` keyword as one of the arguments.
330
331 ``FETCHCONTENT_MAKEAVAILABE_SERIAL``
332   The ``<method-specific-args>`` will be everything passed to the
333   :command:`FetchContent_Declare` call that corresponds to the requested
334   dependency, with the following exceptions:
335
336   * If ``SOURCE_DIR`` or ``BINARY_DIR`` were not part of the original
337     declared arguments, they will be added with their default values.
338   * If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is set to ``NEVER``,
339     any ``FIND_PACKAGE_ARGS`` will be omitted.
340   * The ``OVERRIDE_FIND_PACKAGE`` keyword is always omitted.
341
342   The first of the ``<method-specific-args>`` will always be the name of the
343   dependency.  Dependency names are case-insensitive for this method because
344   :module:`FetchContent` also treats them case-insensitively.
345
346   If the provider fulfills the request, it should call
347   :command:`FetchContent_SetPopulated`, passing the name of the dependency as
348   the first argument.  The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments to that
349   command should only be given if the provider makes the dependency's source
350   and build directories available in exactly the same way as the built-in
351   :command:`FetchContent_MakeAvailable` command.
352
353   If the provider returns without calling :command:`FetchContent_SetPopulated`
354   for the named dependency, CMake will assume the request was not fulfilled
355   and will fall back to the built-in implementation.
356
357   Note that empty arguments may be significant for this method (e.g. an empty
358   string following a ``GIT_SUBMODULES`` keyword).  Therefore, if forwarding
359   these arguments on to another command, extra care must be taken to avoid such
360   arguments being silently dropped.
361
362   If ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` is set, then the
363   dependency provider will never see requests for the ``<depName>`` dependency
364   for this method. When the user sets such a variable, they are explicitly
365   overriding where to get that dependency from and are taking on the
366   responsibility that their overriding version meets any requirements for that
367   dependency and is compatible with whatever else in the project uses it.
368   Depending on the value of :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE`
369   and whether the ``OVERRIDE_FIND_PACKAGE`` option was given to
370   :command:`FetchContent_Declare`, having
371   ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` set may also prevent the
372   dependency provider from seeing requests for a ``find_package(depName)``
373   call too.
374
375 Provider Examples
376 """""""""""""""""
377
378 This first example only intercepts :command:`find_package` calls.  The
379 provider command runs an external tool which copies the relevant artifacts
380 into a provider-specific directory, if that tool knows about the dependency.
381 It then relies on the built-in implementation to then find those artifacts.
382 :command:`FetchContent_MakeAvailable` calls would not go through the provider.
383
384 .. code-block:: cmake
385   :caption: mycomp_provider.cmake
386
387   # Always ensure we have the policy settings this provider expects
388   cmake_minimum_required(VERSION 3.24)
389
390   set(MYCOMP_PROVIDER_INSTALL_DIR ${CMAKE_BINARY_DIR}/mycomp_packages
391     CACHE PATH "The directory this provider installs packages to"
392   )
393   # Tell the built-in implementation to look in our area first, unless
394   # the find_package() call uses NO_..._PATH options to exclude it
395   list(APPEND CMAKE_MODULE_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}/cmake)
396   list(APPEND CMAKE_PREFIX_PATH ${MYCOMP_PROVIDER_INSTALL_DIR})
397
398   macro(mycomp_provide_dependency method package_name)
399     execute_process(
400       COMMAND some_tool ${package_name} --installdir ${MYCOMP_PROVIDER_INSTALL_DIR}
401       COMMAND_ERROR_IS_FATAL ANY
402     )
403   endmacro()
404
405   cmake_language(
406     SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
407     SUPPORTED_METHODS FIND_PACKAGE
408   )
409
410 The user would then typically use the above file like so::
411
412   cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/mycomp_provider.cmake ...
413
414 The next example demonstrates a provider that accepts both methods, but
415 only handles one specific dependency.  It enforces providing Google Test
416 using :module:`FetchContent`, but leaves all other dependencies to be
417 fulfilled by CMake's built-in implementation.  It accepts a few different
418 names, which demonstrates one way of working around projects that hard-code
419 an unusual or undesirable way of adding this particular dependency to the
420 build.  The example also demonstrates how to use the :command:`list` command
421 to preserve variables that may be overwritten by a call to
422 :command:`FetchContent_MakeAvailable`.
423
424 .. code-block:: cmake
425   :caption: mycomp_provider.cmake
426
427   cmake_minimum_required(VERSION 3.24)
428
429   # Because we declare this very early, it will take precedence over any
430   # details the project might declare later for the same thing
431   include(FetchContent)
432   FetchContent_Declare(
433     googletest
434     GIT_REPOSITORY https://github.com/google/googletest.git
435     GIT_TAG        e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
436   )
437
438   # Both FIND_PACKAGE and FETCHCONTENT_MAKEAVAILABLE_SERIAL methods provide
439   # the package or dependency name as the first method-specific argument.
440   macro(mycomp_provide_dependency method dep_name)
441     if("${dep_name}" MATCHES "^(gtest|googletest)$")
442       # Save our current command arguments in case we are called recursively
443       list(APPEND mycomp_provider_args ${method} ${dep_name})
444
445       # This will forward to the built-in FetchContent implementation,
446       # which detects a recursive call for the same thing and avoids calling
447       # the provider again if dep_name is the same as the current call.
448       FetchContent_MakeAvailable(googletest)
449
450       # Restore our command arguments
451       list(POP_BACK mycomp_provider_args dep_name method)
452
453       # Tell the caller we fulfilled the request
454       if("${method}" STREQUAL "FIND_PACKAGE")
455         # We need to set this if we got here from a find_package() call
456         # since we used a different method to fulfill the request.
457         # This example assumes projects only use the gtest targets,
458         # not any of the variables the FindGTest module may define.
459         set(${dep_name}_FOUND TRUE)
460       elseif(NOT "${dep_name}" STREQUAL "googletest")
461         # We used the same method, but were given a different name to the
462         # one we populated with. Tell the caller about the name it used.
463         FetchContent_SetPopulated(${dep_name}
464           SOURCE_DIR "${googletest_SOURCE_DIR}"
465           BINARY_DIR "${googletest_BINARY_DIR}"
466         )
467       endif()
468     endif()
469   endmacro()
470
471   cmake_language(
472     SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
473     SUPPORTED_METHODS
474       FIND_PACKAGE
475       FETCHCONTENT_MAKEAVAILABLE_SERIAL
476   )
477
478 The final example demonstrates how to modify arguments to a
479 :command:`find_package` call.  It forces all such calls to have the
480 ``QUIET`` keyword.  It uses the ``BYPASS_PROVIDER`` keyword to prevent
481 calling the provider command recursively for the same dependency.
482
483 .. code-block:: cmake
484   :caption: mycomp_provider.cmake
485
486   cmake_minimum_required(VERSION 3.24)
487
488   macro(mycomp_provide_dependency method)
489     find_package(${ARGN} BYPASS_PROVIDER QUIET)
490   endmacro()
491
492   cmake_language(
493     SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
494     SUPPORTED_METHODS FIND_PACKAGE
495   )
496
497 Getting current message log level
498 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
499
500 .. versionadded:: 3.25
501
502 .. _GET_MESSAGE_LOG_LEVEL:
503 .. _query_message_log_level:
504
505 .. code-block:: cmake
506
507   cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)
508
509 Writes the current :command:`message` logging level
510 into the given ``<output_variable>``.
511
512 See :command:`message` for the possible logging levels.
513
514 The current message logging level can be set either using the
515 :option:`--log-level <cmake --log-level>`
516 command line option of the :manual:`cmake(1)` program or using
517 the :variable:`CMAKE_MESSAGE_LOG_LEVEL` variable.
518
519 If both the command line option and the variable are set, the command line
520 option takes precedence. If neither are set, the default logging level
521 is returned.