-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathCorrosion.cmake
2255 lines (1979 loc) · 101 KB
/
Corrosion.cmake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
cmake_minimum_required(VERSION 3.22)
list(APPEND CMAKE_MESSAGE_CONTEXT "Corrosion")
message(DEBUG "Using Corrosion ${Corrosion_VERSION} with CMake ${CMAKE_VERSION} "
"and the `${CMAKE_GENERATOR}` Generator"
)
get_cmake_property(COR_IS_MULTI_CONFIG GENERATOR_IS_MULTI_CONFIG)
set(COR_IS_MULTI_CONFIG "${COR_IS_MULTI_CONFIG}" CACHE BOOL "Do not change this" FORCE)
mark_as_advanced(FORCE COR_IS_MULTI_CONFIG)
if(NOT COR_IS_MULTI_CONFIG AND DEFINED CMAKE_CONFIGURATION_TYPES)
message(WARNING "The Generator is ${CMAKE_GENERATOR}, which is not a multi-config "
"Generator, but CMAKE_CONFIGURATION_TYPES is set. Please don't set "
"CMAKE_CONFIGURATION_TYPES unless you are using a multi-config Generator."
)
endif()
option(CORROSION_VERBOSE_OUTPUT "Enables verbose output from Corrosion and Cargo" OFF)
if(DEFINED CORROSION_RESPECT_OUTPUT_DIRECTORY AND NOT CORROSION_RESPECT_OUTPUT_DIRECTORY)
message(WARNING "The option CORROSION_RESPECT_OUTPUT_DIRECTORY was removed."
" Corrosion now always attempts to respect the output directory.")
endif()
option(
CORROSION_NO_WARN_PARSE_TARGET_TRIPLE_FAILED
"Surpresses a warning if the parsing the target triple failed."
OFF
)
find_package(Rust REQUIRED)
if(CMAKE_GENERATOR MATCHES "Visual Studio"
AND (NOT CMAKE_VS_PLATFORM_NAME STREQUAL CMAKE_VS_PLATFORM_NAME_DEFAULT)
AND Rust_VERSION VERSION_LESS "1.54")
message(FATAL_ERROR "Due to a cargo issue, cross-compiling with a Visual Studio generator and rust versions"
" before 1.54 is not supported. Rust build scripts would be linked with the cross-compiler linker, which"
" causes the build to fail. Please upgrade your Rust version to 1.54 or newer.")
endif()
# message(STATUS "Using Corrosion as a subdirectory")
get_property(
RUSTC_EXECUTABLE
TARGET Rust::Rustc PROPERTY IMPORTED_LOCATION
)
get_property(
CARGO_EXECUTABLE
TARGET Rust::Cargo PROPERTY IMPORTED_LOCATION
)
if(Rust_TOOLCHAIN_IS_RUSTUP_MANAGED AND DEFINED Rust_RUSTUP_TOOLCHAINS)
set(corrosion_tools_rust_toolchain_docstring "Rust toolchain to use for building helper tools such as cbindgen or cxx-bridge")
if(DEFINED CORROSION_TOOLS_RUST_TOOLCHAIN)
set(cor_default_tools_toolchain "${CORROSION_TOOLS_RUST_TOOLCHAIN}")
else()
set(cor_default_tools_toolchain "${Rust_TOOLCHAIN}")
endif()
set(CORROSION_TOOLS_RUST_TOOLCHAIN "${cor_default_tools_toolchain}" CACHE STRING
"${corrosion_tools_rust_toolchain_docstring}" FORCE)
set_property(CACHE CORROSION_TOOLS_RUST_TOOLCHAIN PROPERTY STRINGS "${Rust_RUSTUP_TOOLCHAINS}")
if(NOT "$CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN}" IN_LIST Rust_RUSTUP_TOOLCHAINS)
if("$CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN}-${Rust_CARGO_HOST_TARGET}" IN_LIST Rust_RUSTUP_TOOLCHAINS)
set(CORROSION_TOOLS_RUST_TOOLCHAIN "$CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN}-${Rust_CARGO_HOST_TARGET}"
CACHE PATH "${corrosion_tools_rust_toolchain_docstring}" FORCE)
else()
message(FATAL_ERROR "CORROSION_TOOLS_RUST_TOOLCHAIN must be set to a valid rustup managed toolchain path."
"Rust_RUSTUP_TOOLCHAINS contains a list of valid installed toolchains."
)
endif()
endif()
foreach(toolchain tc_rustc tc_cargo IN ZIP_LISTS Rust_RUSTUP_TOOLCHAINS Rust_RUSTUP_TOOLCHAINS_RUSTC_PATH Rust_RUSTUP_TOOLCHAINS_CARGO_PATH)
if("${toolchain}" STREQUAL $CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN})
# Minimum CMake version 3.29 for `IS_EXECUTABLE`.
if(NOT (tc_cargo AND tc_rustc ))
message(FATAL_ERROR "Failed to find executable rustc or cargo for toolchain `$CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN}`")
endif()
set(CORROSION_TOOLS_RUSTC "${tc_rustc}" CACHE INTERNAL "" FORCE)
set(CORROSION_TOOLS_CARGO "${tc_cargo}" CACHE INTERNAL "" FORCE)
break()
endif()
endforeach()
if(NOT DEFINED CACHE{CORROSION_TOOLS_CARGO})
message(FATAL_ERROR "Internal error: Failed to find toolchain $CACHE{CORROSION_TOOLS_RUST_TOOLCHAIN} in "
"list of rustup managed toolchains: ${Rust_RUSTUP_TOOLCHAINS}"
)
endif()
else()
# Fallback to the default project toolchain if rust is not rustup managed.
if(DEFINED CORROSION_TOOLS_RUST_TOOLCHAIN)
message(DEBUG "Ignoring `CORROSION_TOOLS_RUST_TOOLCHAIN=${CORROSION_TOOLS_RUST_TOOLCHAIN}` "
"since the toolchains are not rustup managed. Falling back to the default rust toolchain"
" for this project."
)
endif()
set(CORROSION_TOOLS_RUSTC "${RUSTC_EXECUTABLE}" CACHE INTERNAL "" FORCE)
set(CORROSION_TOOLS_CARGO "${CARGO_EXECUTABLE}" CACHE INTERNAL "" FORCE)
endif()
function(_corrosion_bin_target_suffix target_name out_var_suffix)
get_target_property(hostbuild "${target_name}" ${_CORR_PROP_HOST_BUILD})
if((hostbuild AND CMAKE_HOST_WIN32)
OR ((NOT hostbuild) AND (Rust_CARGO_TARGET_OS STREQUAL "windows")))
set(_suffix ".exe")
elseif(Rust_CARGO_TARGET_OS STREQUAL "vxworks")
set(_suffix ".vxe")
else()
set(_suffix "")
endif()
set(${out_var_suffix} "${_suffix}" PARENT_SCOPE)
endfunction()
# Do not call this function directly!
#
# This function should be called deferred to evaluate target properties late in the configure stage.
# IMPORTED_LOCATION does not support Generator expressions, so we must evaluate the output
# directory target property value at configure time. This function must be deferred to the end of
# the configure stage, so we can be sure that the output directory is not modified afterwards.
function(_corrosion_set_imported_location_deferred target_name base_property output_directory_property filename)
# The output directory property is expected to be set on the exposed target (without postfix),
# but we need to set the imported location on the actual library target with postfix.
if("${target_name}" MATCHES "^(.+)-(static|shared)$")
set(output_dir_prop_target_name "${CMAKE_MATCH_1}")
else()
set(output_dir_prop_target_name "${target_name}")
endif()
# Append .exe suffix for executable by-products if the target is windows or if it's a host
# build and the host is Windows.
get_target_property(target_type ${target_name} TYPE)
if(${target_type} STREQUAL "EXECUTABLE" AND (NOT "${filename}" MATCHES "\.pdb$"))
_corrosion_bin_target_suffix(${target_name} "suffix")
string(APPEND filename "${suffix}")
endif()
get_target_property(output_directory "${output_dir_prop_target_name}" "${output_directory_property}")
message(DEBUG "Output directory property (target ${output_dir_prop_target_name}): ${output_directory_property} dir: ${output_directory}")
foreach(config_type ${CMAKE_CONFIGURATION_TYPES})
string(TOUPPER "${config_type}" config_type_upper)
get_target_property(output_dir_curr_config ${output_dir_prop_target_name}
"${output_directory_property}_${config_type_upper}"
)
if(output_dir_curr_config)
set(curr_out_dir "${output_dir_curr_config}")
elseif(output_directory)
string(GENEX_STRIP "${output_directory}" output_dir_no_genex)
# Only add config dir if there is no genex in here. See
# https://cmake.org/cmake/help/latest/prop_tgt/RUNTIME_OUTPUT_DIRECTORY.html
if(output_directory STREQUAL output_dir_no_genex)
set(curr_out_dir "${output_directory}/${config_type}")
else()
set(curr_out_dir "${output_directory}")
endif()
else()
set(curr_out_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif()
string(REPLACE "\$<CONFIG>" "${config_type}" curr_out_dir "${curr_out_dir}")
message(DEBUG "Setting ${base_property}_${config_type_upper} for target ${target_name}"
" to `${curr_out_dir}/${filename}`.")
string(GENEX_STRIP "${curr_out_dir}" stripped_out_dir)
if(NOT ("${stripped_out_dir}" STREQUAL "${curr_out_dir}"))
message(FATAL_ERROR "${output_directory_property} for target ${output_dir_prop_target_name} "
"contained an unexpected Generator expression. Output dir: `${curr_out_dir}`"
"Note: Corrosion only supports the `\$<CONFIG>` generator expression for output directories.")
endif()
# For Multiconfig we want to specify the correct location for each configuration
set_property(
TARGET ${target_name}
PROPERTY "${base_property}_${config_type_upper}"
"${curr_out_dir}/${filename}"
)
set(base_output_directory "${curr_out_dir}")
endforeach()
if(NOT COR_IS_MULTI_CONFIG)
if(output_directory)
set(base_output_directory "${output_directory}")
else()
set(base_output_directory "${CMAKE_CURRENT_BINARY_DIR}")
endif()
string(REPLACE "\$<CONFIG>" "${CMAKE_BUILD_TYPE}" base_output_directory "${base_output_directory}")
string(GENEX_STRIP "${base_output_directory}" stripped_out_dir)
if(NOT ("${stripped_out_dir}" STREQUAL "${base_output_directory}"))
message(FATAL_ERROR "${output_dir_prop_target_name} for target ${output_dir_prop_target_name} "
"contained an unexpected Generator expression. Output dir: `${base_output_directory}`"
"Note: Corrosion only supports the `\$<CONFIG>` generator expression for output directories.")
endif()
endif()
message(DEBUG "Setting ${base_property} for target ${target_name}"
" to `${base_output_directory}/${filename}`.")
# IMPORTED_LOCATION must be set regardless of possible overrides. In the multiconfig case,
# the last configuration "wins" (IMPORTED_LOCATION is not documented to have Genex support).
set_property(
TARGET ${target_name}
PROPERTY "${base_property}" "${base_output_directory}/${filename}"
)
endfunction()
# Set the imported location of a Rust target.
#
# Rust targets are built via custom targets / custom commands. The actual artifacts are exposed
# to CMake as imported libraries / executables that depend on the cargo_build command. For CMake
# to find the built artifact we need to set the IMPORTED location to the actual location on disk.
# Corrosion tries to copy the artifacts built by cargo to standard locations. The IMPORTED_LOCATION
# is set to point to the copy, and not the original from the cargo build directory.
#
# Parameters:
# - target_name: Name of the Rust target
# - base_property: Name of the base property - i.e. `IMPORTED_LOCATION` or `IMPORTED_IMPLIB`.
# - output_directory_property: Target property name that determines the standard location for the
# artifact.
# - filename of the artifact.
function(_corrosion_set_imported_location target_name base_property output_directory_property filename)
cmake_language(EVAL CODE "
cmake_language(DEFER
CALL
_corrosion_set_imported_location_deferred
[[${target_name}]]
[[${base_property}]]
[[${output_directory_property}]]
[[${filename}]]
)
")
endfunction()
function(_corrosion_copy_byproduct_deferred target_name output_dir_prop_names cargo_build_dir file_names)
if(ARGN)
message(FATAL_ERROR "Unexpected additional arguments")
endif()
foreach(output_dir_prop_name ${output_dir_prop_names})
get_target_property(output_dir ${target_name} "${output_dir_prop_name}")
if(output_dir)
break()
endif()
endforeach()
# A Genex expanding to the output directory depending on the configuration.
set(multiconfig_out_dir_genex "")
foreach(config_type ${CMAKE_CONFIGURATION_TYPES})
string(TOUPPER "${config_type}" config_type_upper)
foreach(output_dir_prop_name ${output_dir_prop_names})
get_target_property(output_dir_curr_config ${target_name} "${output_dir_prop_name}_${config_type_upper}")
if(output_dir_curr_config)
break()
endif()
endforeach()
if(output_dir_curr_config)
set(curr_out_dir "${output_dir_curr_config}")
elseif(output_dir)
# Fallback to `output_dir` if specified
# Note: Multi-configuration generators append a per-configuration subdirectory to the
# specified directory unless a generator expression is used (from CMake documentation).
set(curr_out_dir "${output_dir}/${config_type}")
else()
# Fallback to the default directory. We do not append the configuration directory here
# and instead let CMake do this, since otherwise the resolving of dynamic library
# imported paths may fail.
set(curr_out_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif()
set(multiconfig_out_dir_genex "${multiconfig_out_dir_genex}$<$<CONFIG:${config_type}>:${curr_out_dir}>")
endforeach()
if(COR_IS_MULTI_CONFIG)
set(output_dir "${multiconfig_out_dir_genex}")
else()
if(NOT output_dir)
# Fallback to default directory.
set(output_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif()
endif()
# Append .exe suffix for executable by-products if the target is windows or if it's a host
# build and the host is Windows.
get_target_property(target_type "${target_name}" TYPE)
if (target_type STREQUAL "EXECUTABLE")
list(LENGTH file_names list_len)
if(NOT list_len EQUAL "1")
message(FATAL_ERROR
"Internal error: Exactly one filename should be passed for executable types.")
endif()
_corrosion_bin_target_suffix(${target_name} "suffix")
if(suffix AND (NOT "${file_names}" MATCHES "\.pdb$"))
# For executable targets we know / checked that only one file will be passed.
string(APPEND file_names "${suffix}")
endif()
endif()
set(src_file_names "${file_names}")
if(Rust_CARGO_TARGET_ENV STREQUAL "gnullvm")
# Workaround for cargo not exposing implibs yet.
list(TRANSFORM src_file_names PREPEND "deps/" REGEX "\.dll\.a$")
endif()
list(TRANSFORM src_file_names PREPEND "${cargo_build_dir}/")
list(TRANSFORM file_names PREPEND "${output_dir}/" OUTPUT_VARIABLE dst_file_names)
message(DEBUG "Adding command to copy byproducts `${file_names}` to ${dst_file_names}")
add_custom_command(TARGET _cargo-build_${target_name}
POST_BUILD
# output_dir may contain a Generator expression.
COMMAND ${CMAKE_COMMAND} -E make_directory "${output_dir}"
COMMAND
${CMAKE_COMMAND} -E copy_if_different
# tested to work with both multiple files and paths with spaces
${src_file_names}
"${output_dir}"
BYPRODUCTS ${dst_file_names}
COMMENT "Copying byproducts `${file_names}` to ${output_dir}"
VERBATIM
COMMAND_EXPAND_LISTS
)
endfunction()
# Copy the artifacts generated by cargo to the appropriate destination.
#
# Parameters:
# - target_name: The name of the Rust target
# - output_dir_prop_names: The property name(s) controlling the destination (e.g.
# `LIBRARY_OUTPUT_DIRECTORY` or `PDB_OUTPUT_DIRECTORY;RUNTIME_OUTPUT_DIRECTORY`)
# - cargo_build_dir: the directory cargo build places it's output artifacts in.
# - filenames: the file names of any output artifacts as a list.
function(_corrosion_copy_byproducts target_name output_dir_prop_names cargo_build_dir file_names)
cmake_language(EVAL CODE "
cmake_language(DEFER
CALL
_corrosion_copy_byproduct_deferred
[[${target_name}]]
[[${output_dir_prop_names}]]
[[${cargo_build_dir}]]
[[${file_names}]]
)
")
endfunction()
# Add targets for the static and/or shared libraries of the rust target.
# The generated byproduct names are returned via the `OUT_<type>_BYPRODUCTS` arguments.
function(_corrosion_add_library_target)
set(OPTIONS "")
set(ONE_VALUE_KEYWORDS
WORKSPACE_MANIFEST_PATH
TARGET_NAME
OUT_ARCHIVE_OUTPUT_BYPRODUCTS
OUT_SHARED_LIB_BYPRODUCTS
OUT_PDB_BYPRODUCT
)
set(MULTI_VALUE_KEYWORDS LIB_KINDS)
cmake_parse_arguments(PARSE_ARGV 0 CALT "${OPTIONS}" "${ONE_VALUE_KEYWORDS}" "${MULTI_VALUE_KEYWORDS}")
if(DEFINED CALT_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Internal error - unexpected arguments: ${CALT_UNPARSED_ARGUMENTS}")
elseif(DEFINED CALT_KEYWORDS_MISSING_VALUES)
message(FATAL_ERROR "Internal error - the following keywords had no associated value(s):"
"${CALT_KEYWORDS_MISSING_VALUES}")
endif()
list(TRANSFORM ONE_VALUE_KEYWORDS PREPEND CALT_ OUTPUT_VARIABLE required_arguments)
foreach(required_argument ${required_arguments} )
if(NOT DEFINED "${required_argument}")
message(FATAL_ERROR "Internal error: Missing required argument ${required_argument}."
"Complete argument list: ${ARGN}"
)
endif()
endforeach()
if("staticlib" IN_LIST CALT_LIB_KINDS)
set(has_staticlib TRUE)
endif()
if("cdylib" IN_LIST CALT_LIB_KINDS)
set(has_cdylib TRUE)
endif()
if(NOT (has_staticlib OR has_cdylib))
message(FATAL_ERROR "Unknown library type(s): ${CALT_LIB_KINDS}")
endif()
set(workspace_manifest_path "${CALT_WORKSPACE_MANIFEST_PATH}")
set(target_name "${CALT_TARGET_NAME}")
set(is_windows "")
set(is_windows_gnu "")
set(is_windows_msvc "")
set(is_macos "")
if(Rust_CARGO_TARGET_OS STREQUAL "windows")
set(is_windows TRUE)
if(Rust_CARGO_TARGET_ENV STREQUAL "msvc")
set(is_windows_msvc TRUE)
elseif(Rust_CARGO_TARGET_ENV STREQUAL "gnu" OR Rust_CARGO_TARGET_ENV STREQUAL "gnullvm")
set(is_windows_gnu TRUE)
endif()
elseif(Rust_CARGO_TARGET_OS STREQUAL "darwin")
set(is_macos TRUE)
endif()
# target file names
string(REPLACE "-" "_" lib_name "${target_name}")
if(is_windows_msvc)
set(static_lib_name "${lib_name}.lib")
else()
set(static_lib_name "lib${lib_name}.a")
endif()
if(is_windows)
set(dynamic_lib_name "${lib_name}.dll")
elseif(is_macos)
set(dynamic_lib_name "lib${lib_name}.dylib")
else()
set(dynamic_lib_name "lib${lib_name}.so")
endif()
if(is_windows_msvc)
set(implib_name "${lib_name}.dll.lib")
elseif(is_windows_gnu)
set(implib_name "lib${lib_name}.dll.a")
elseif(is_windows)
message(FATAL_ERROR "Unknown windows environment - Can't determine implib name")
endif()
set(pdb_name "${lib_name}.pdb")
set(archive_output_byproducts "")
if(has_staticlib)
list(APPEND archive_output_byproducts ${static_lib_name})
endif()
if(has_cdylib)
set("${CALT_OUT_SHARED_LIB_BYPRODUCTS}" "${dynamic_lib_name}" PARENT_SCOPE)
if(is_windows)
list(APPEND archive_output_byproducts ${implib_name})
endif()
if(is_windows_msvc)
set("${CALT_OUT_PDB_BYPRODUCT}" "${pdb_name}" PARENT_SCOPE)
endif()
endif()
set("${CALT_OUT_ARCHIVE_OUTPUT_BYPRODUCTS}" "${archive_output_byproducts}" PARENT_SCOPE)
if(has_staticlib)
add_library(${target_name}-static STATIC IMPORTED GLOBAL)
add_dependencies(${target_name}-static cargo-build_${target_name})
set_target_properties(${target_name}-static PROPERTIES COR_FILE_NAME ${static_lib_name})
_corrosion_set_imported_location("${target_name}-static" "IMPORTED_LOCATION"
"ARCHIVE_OUTPUT_DIRECTORY"
"${static_lib_name}")
# Todo: NO_STD target property?
if(NOT COR_NO_STD)
set_property(
TARGET ${target_name}-static
PROPERTY INTERFACE_LINK_LIBRARIES ${Rust_CARGO_TARGET_LINK_NATIVE_LIBS}
)
set_property(
TARGET ${target_name}-static
PROPERTY INTERFACE_LINK_OPTIONS ${Rust_CARGO_TARGET_LINK_OPTIONS}
)
if(is_macos)
set_property(TARGET ${target_name}-static
PROPERTY INTERFACE_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
)
endif()
endif()
endif()
if(has_cdylib)
add_library(${target_name}-shared SHARED IMPORTED GLOBAL)
add_dependencies(${target_name}-shared cargo-build_${target_name})
set_target_properties(${target_name}-shared PROPERTIES COR_FILE_NAME ${dynamic_lib_name})
# Todo: (Not new issue): What about IMPORTED_SONAME and IMPORTED_NO_SYSTEM?
_corrosion_set_imported_location("${target_name}-shared" "IMPORTED_LOCATION"
"LIBRARY_OUTPUT_DIRECTORY"
"${dynamic_lib_name}"
)
# In the future we would probably prefer to let Rust set the soname for packages >= 1.0.
# This is tracked in issue #333.
set_target_properties(${target_name}-shared PROPERTIES IMPORTED_NO_SONAME TRUE)
if(is_windows)
_corrosion_set_imported_location("${target_name}-shared" "IMPORTED_IMPLIB"
"ARCHIVE_OUTPUT_DIRECTORY"
"${implib_name}"
)
set_target_properties(${target_name}-shared PROPERTIES COR_IMPLIB_FILE_NAME ${implib_name})
endif()
if(is_macos)
set_property(TARGET ${target_name}-shared
PROPERTY INTERFACE_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
)
endif()
endif()
if(has_cdylib AND has_staticlib)
if(BUILD_SHARED_LIBS)
target_link_libraries(${target_name} INTERFACE ${target_name}-shared)
else()
target_link_libraries(${target_name} INTERFACE ${target_name}-static)
endif()
elseif(has_cdylib)
target_link_libraries(${target_name} INTERFACE ${target_name}-shared)
else()
target_link_libraries(${target_name} INTERFACE ${target_name}-static)
endif()
endfunction()
function(_corrosion_add_bin_target workspace_manifest_path bin_name out_bin_byproduct out_pdb_byproduct)
if(NOT bin_name)
message(FATAL_ERROR "No bin_name in _corrosion_add_bin_target for target ${target_name}")
endif()
string(REPLACE "-" "_" bin_name_underscore "${bin_name}")
set(pdb_name "${bin_name_underscore}.pdb")
if(Rust_CARGO_TARGET_ENV STREQUAL "msvc")
set(${out_pdb_byproduct} "${pdb_name}" PARENT_SCOPE)
endif()
# Potential .exe suffix will be added later, also depending on possible hostbuild
# target property
set(bin_filename "${bin_name}")
set(${out_bin_byproduct} "${bin_filename}" PARENT_SCOPE)
add_dependencies(${bin_name} cargo-build_${bin_name})
if(Rust_CARGO_TARGET_OS STREQUAL "darwin")
set_property(TARGET ${bin_name}
PROPERTY INTERFACE_LINK_DIRECTORIES "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
)
endif()
_corrosion_set_imported_location("${bin_name}" "IMPORTED_LOCATION"
"RUNTIME_OUTPUT_DIRECTORY"
"${bin_filename}"
)
endfunction()
include(CorrosionGenerator)
# Note: `cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)` requires CMake 3.25,
# so we offer our own option to control verbosity of downstream commands (e.g. cargo build)
if (CORROSION_VERBOSE_OUTPUT)
set(_CORROSION_VERBOSE_OUTPUT_FLAG --verbose CACHE INTERNAL "")
else()
# We want to silence some less important commands by default.
set(_CORROSION_QUIET_OUTPUT_FLAG --quiet CACHE INTERNAL "")
endif()
set(_CORROSION_CARGO_VERSION ${Rust_CARGO_VERSION} CACHE INTERNAL "cargo version used by corrosion")
set(_CORROSION_RUST_CARGO_TARGET ${Rust_CARGO_TARGET} CACHE INTERNAL "target triple used by corrosion")
set(_CORROSION_RUST_CARGO_HOST_TARGET ${Rust_CARGO_HOST_TARGET} CACHE INTERNAL "host triple used by corrosion")
set(_CORROSION_RUSTC "${RUSTC_EXECUTABLE}" CACHE INTERNAL "Path to rustc used by corrosion")
set(_CORROSION_CARGO "${CARGO_EXECUTABLE}" CACHE INTERNAL "Path to cargo used by corrosion")
string(REPLACE "-" "_" _CORROSION_RUST_CARGO_TARGET_UNDERSCORE "${Rust_CARGO_TARGET}")
set(_CORROSION_RUST_CARGO_TARGET_UNDERSCORE "${_CORROSION_RUST_CARGO_TARGET_UNDERSCORE}" CACHE INTERNAL "lowercase target triple with underscores")
string(TOUPPER "${_CORROSION_RUST_CARGO_TARGET_UNDERSCORE}" _CORROSION_TARGET_TRIPLE_UPPER)
set(_CORROSION_RUST_CARGO_TARGET_UPPER
"${_CORROSION_TARGET_TRIPLE_UPPER}"
CACHE INTERNAL
"target triple in uppercase with underscore"
)
# We previously specified some Custom properties as part of our public API, however the chosen names prevented us from
# supporting CMake versions before 3.19. In order to both support older CMake versions and not break existing code
# immediately, we are using a different property name depending on the CMake version. However users avoid using
# any of the properties directly, as they are no longer part of the public API and are to be considered deprecated.
# Instead use the corrosion_set_... functions as documented in the Readme.
set(_CORR_PROP_FEATURES CORROSION_FEATURES CACHE INTERNAL "")
set(_CORR_PROP_ALL_FEATURES CORROSION_ALL_FEATURES CACHE INTERNAL "")
set(_CORR_PROP_NO_DEFAULT_FEATURES CORROSION_NO_DEFAULT_FEATURES CACHE INTERNAL "")
set(_CORR_PROP_ENV_VARS CORROSION_ENVIRONMENT_VARIABLES CACHE INTERNAL "")
set(_CORR_PROP_HOST_BUILD CORROSION_USE_HOST_BUILD CACHE INTERNAL "")
# Add custom command to build one target in a package (crate)
#
# A target may be either a specific bin
function(_add_cargo_build out_cargo_build_out_dir)
set(options NO_LINKER_OVERRIDE)
set(one_value_args PACKAGE TARGET MANIFEST_PATH WORKSPACE_MANIFEST_PATH)
set(multi_value_args BYPRODUCTS TARGET_KINDS)
cmake_parse_arguments(
ACB
"${options}"
"${one_value_args}"
"${multi_value_args}"
${ARGN}
)
if(DEFINED ACB_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Internal error - unexpected arguments: "
${ACB_UNPARSED_ARGUMENTS})
elseif(DEFINED ACB_KEYWORDS_MISSING_VALUES)
message(FATAL_ERROR "Internal error - missing values for the following arguments: "
${ACB_KEYWORDS_MISSING_VALUES})
endif()
set(package_name "${ACB_PACKAGE}")
set(target_name "${ACB_TARGET}")
set(path_to_toml "${ACB_MANIFEST_PATH}")
set(target_kinds "${ACB_TARGET_KINDS}")
set(workspace_manifest_path "${ACB_WORKSPACE_MANIFEST_PATH}")
set(build_byproducts "${ACB_BYPRODUCTS}")
unset(cargo_rustc_crate_types)
if(NOT target_kinds)
message(FATAL_ERROR "TARGET_KINDS not specified")
elseif("staticlib" IN_LIST target_kinds OR "cdylib" IN_LIST target_kinds)
set(cargo_rustc_filter "--lib")
if("${Rust_VERSION}" VERSION_GREATER_EQUAL "1.64")
# https://doc.rust-lang.org/1.64.0/cargo/commands/cargo-rustc.html
# `--crate-type` is documented since Rust 1.64 for `cargo rustc`.
# We just unconditionally set it when available, to support overriding the crate type.
# Due to https://github.com/rust-lang/cargo/issues/14498 we can't use one argument and pass a
# comma seperated list. Instead we use multiple arguments.
set(cargo_rustc_crate_types "${target_kinds}")
list(TRANSFORM cargo_rustc_crate_types PREPEND "--crate-type=")
endif()
elseif("bin" IN_LIST target_kinds)
set(cargo_rustc_filter "--bin=${target_name}")
else()
message(FATAL_ERROR "TARGET_KINDS contained unknown kind `${target_kind}`")
endif()
if (NOT IS_ABSOLUTE "${path_to_toml}")
set(path_to_toml "${CMAKE_SOURCE_DIR}/${path_to_toml}")
endif()
get_filename_component(workspace_toml_dir ${path_to_toml} DIRECTORY )
if (CMAKE_VS_PLATFORM_NAME)
set (build_dir "${CMAKE_VS_PLATFORM_NAME}/$<CONFIG>")
elseif(COR_IS_MULTI_CONFIG)
set (build_dir "$<CONFIG>")
else()
set (build_dir .)
endif()
# If a CMake sysroot is specified, forward it to the linker rustc invokes, too. CMAKE_SYSROOT is documented
# to be passed via --sysroot, so we assume that when it's set, the linker supports this option in that style.
if(CMAKE_CROSSCOMPILING AND CMAKE_SYSROOT)
set(corrosion_link_args "--sysroot=${CMAKE_SYSROOT}")
endif()
if(COR_ALL_FEATURES)
set(all_features_arg --all-features)
endif()
if(COR_NO_DEFAULT_FEATURES)
set(no_default_features_arg --no-default-features)
endif()
if(COR_NO_USES_TERMINAL)
unset(cor_uses_terminal)
else()
set(cor_uses_terminal USES_TERMINAL)
endif()
set(global_rustflags_target_property "$<TARGET_GENEX_EVAL:${target_name},$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_RUSTFLAGS>>")
set(local_rustflags_target_property "$<TARGET_GENEX_EVAL:${target_name},$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_LOCAL_RUSTFLAGS>>")
# todo: this probably should be TARGET_GENEX_EVAL
set(features_target_property "$<GENEX_EVAL:$<TARGET_PROPERTY:${target_name},${_CORR_PROP_FEATURES}>>")
set(features_genex "$<$<BOOL:${features_target_property}>:--features=$<JOIN:${features_target_property},$<COMMA>>>")
# target property overrides corrosion_import_crate argument
set(all_features_target_property "$<GENEX_EVAL:$<TARGET_PROPERTY:${target_name},${_CORR_PROP_ALL_FEATURES}>>")
set(all_features_arg "$<$<BOOL:${all_features_target_property}>:--all-features>")
set(no_default_features_target_property "$<GENEX_EVAL:$<TARGET_PROPERTY:${target_name},${_CORR_PROP_NO_DEFAULT_FEATURES}>>")
set(no_default_features_arg "$<$<BOOL:${no_default_features_target_property}>:--no-default-features>")
set(build_env_variable_genex "$<GENEX_EVAL:$<TARGET_PROPERTY:${target_name},${_CORR_PROP_ENV_VARS}>>")
set(hostbuild_override "$<BOOL:$<TARGET_PROPERTY:${target_name},${_CORR_PROP_HOST_BUILD}>>")
set(if_not_host_build_condition "$<NOT:${hostbuild_override}>")
set(corrosion_link_args "$<${if_not_host_build_condition}:${corrosion_link_args}>")
# We always set `--target`, so that cargo always places artifacts into a directory with the
# target triple.
set(cargo_target_option "--target=$<IF:${hostbuild_override},${_CORROSION_RUST_CARGO_HOST_TARGET},${_CORROSION_RUST_CARGO_TARGET}>")
# The target may be a filepath to custom target json file. For host targets we assume that they are built-in targets.
_corrosion_strip_target_triple(${_CORROSION_RUST_CARGO_TARGET} stripped_target_triple)
set(target_artifact_dir "$<IF:${hostbuild_override},${_CORROSION_RUST_CARGO_HOST_TARGET},${stripped_target_triple}>")
set(flags_genex "$<GENEX_EVAL:$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_CARGO_FLAGS>>")
set(explicit_linker_property "$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_LINKER>")
set(explicit_linker_defined "$<BOOL:${explicit_linker_property}>")
set(cargo_profile_target_property "$<TARGET_GENEX_EVAL:${target_name},$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_CARGO_PROFILE>>")
# Option to override the rustc/cargo binary to something other than the global default
set(rustc_override "$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_RUSTC>")
set(cargo_override "$<TARGET_PROPERTY:${target_name},INTERFACE_CORROSION_CARGO>")
set(rustc_bin "$<IF:$<BOOL:${rustc_override}>,${rustc_override},${_CORROSION_RUSTC}>")
set(cargo_bin "$<IF:$<BOOL:${cargo_override}>,${cargo_override},${_CORROSION_CARGO}>")
# Rust will add `-lSystem` as a flag for the linker on macOS. Adding the -L flag via RUSTFLAGS only fixes the
# problem partially - buildscripts still break, since they won't receive the RUSTFLAGS. This seems to only be a
# problem if we specify the linker ourselves (which we do, since this is necessary for e.g. linking C++ code).
# We can however set `LIBRARY_PATH`, which is propagated to the build-script-build properly.
if(NOT CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_NAME STREQUAL "Darwin")
# not needed anymore on macos 13 (and causes issues)
if(${CMAKE_SYSTEM_VERSION} VERSION_LESS 22)
set(cargo_library_path "LIBRARY_PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib")
endif()
elseif(CMAKE_CROSSCOMPILING AND CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
if(${CMAKE_HOST_SYSTEM_VERSION} VERSION_LESS 22)
set(cargo_library_path "$<${hostbuild_override}:LIBRARY_PATH=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib>")
endif()
endif()
set(cargo_profile_set "$<BOOL:${cargo_profile_target_property}>")
# In the default case just specify --release or nothing to stay compatible with
# older rust versions.
set(default_profile_option "$<$<NOT:$<OR:$<CONFIG:Debug>,$<CONFIG:>>>:--release>")
# evaluates to either `--profile=<custom_profile>`, `--release` or nothing (for debug).
set(cargo_profile "$<IF:${cargo_profile_set},--profile=${cargo_profile_target_property},${default_profile_option}>")
# If the profile name is `dev` change the dir name to `debug`.
set(is_dev_profile "$<STREQUAL:${cargo_profile_target_property},dev>")
set(profile_dir_override "$<${is_dev_profile}:debug>")
set(profile_dir_is_overridden "$<BOOL:${profile_dir_override}>")
set(custom_profile_build_type_dir "$<IF:${profile_dir_is_overridden},${profile_dir_override},${cargo_profile_target_property}>")
set(default_build_type_dir "$<IF:$<OR:$<CONFIG:Debug>,$<CONFIG:>>,debug,release>")
set(build_type_dir "$<IF:${cargo_profile_set},${custom_profile_build_type_dir},${default_build_type_dir}>")
set(cargo_target_dir "${CMAKE_BINARY_DIR}/${build_dir}/cargo/build")
set(cargo_build_dir "${cargo_target_dir}/${target_artifact_dir}/${build_type_dir}")
set("${out_cargo_build_out_dir}" "${cargo_build_dir}" PARENT_SCOPE)
set(corrosion_cc_rs_flags)
if(CMAKE_C_COMPILER)
# This variable is read by cc-rs (often used in build scripts) to determine the c-compiler.
# It can still be overridden if the user sets the non underscore variant via the environment variables
# on the target.
list(APPEND corrosion_cc_rs_flags "CC_${_CORROSION_RUST_CARGO_TARGET_UNDERSCORE}=${CMAKE_C_COMPILER}")
endif()
if(CMAKE_CXX_COMPILER)
list(APPEND corrosion_cc_rs_flags "CXX_${_CORROSION_RUST_CARGO_TARGET_UNDERSCORE}=${CMAKE_CXX_COMPILER}")
endif()
# cc-rs doesn't seem to support `llvm-ar` (commandline syntax), wo we might as well just use
# the default AR.
if(CMAKE_AR AND NOT (Rust_CARGO_TARGET_ENV STREQUAL "msvc"))
list(APPEND corrosion_cc_rs_flags "AR_${_CORROSION_RUST_CARGO_TARGET_UNDERSCORE}=${CMAKE_AR}")
endif()
# Since we instruct cc-rs to use the compiler found by CMake, it is likely one that requires also
# specifying the target sysroot to use. CMake's generator makes sure to pass --sysroot with
# CMAKE_OSX_SYSROOT. Fortunately the compilers Apple ships also respect the SDKROOT environment
# variable, which we can set for use when cc-rs invokes the compiler.
if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin" AND CMAKE_OSX_SYSROOT)
list(APPEND corrosion_cc_rs_flags "SDKROOT=${CMAKE_OSX_SYSROOT}")
endif()
# Ensure that cc-rs targets same Apple platform version as the CMake build
if(CMAKE_SYSTEM_NAME STREQUAL "Darwin" AND CMAKE_OSX_DEPLOYMENT_TARGET)
list(APPEND corrosion_cc_rs_flags "MACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET}")
endif()
corrosion_add_target_local_rustflags("${target_name}" "$<$<BOOL:${corrosion_link_args}>:-Clink-args=${corrosion_link_args}>")
# todo: this should probably also be guarded by if_not_host_build_condition.
if(COR_NO_STD)
corrosion_add_target_local_rustflags("${target_name}" "-Cdefault-linker-libraries=no")
else()
corrosion_add_target_local_rustflags("${target_name}" "-Cdefault-linker-libraries=yes")
endif()
set(global_joined_rustflags "$<JOIN:${global_rustflags_target_property}, >")
set(global_rustflags_genex "$<$<BOOL:${global_rustflags_target_property}>:RUSTFLAGS=${global_joined_rustflags}>")
set(local_rustflags_delimiter "$<$<BOOL:${local_rustflags_target_property}>:-->")
set(local_rustflags_genex "$<$<BOOL:${local_rustflags_target_property}>:${local_rustflags_target_property}>")
set(deps_link_languages_prop "$<TARGET_PROPERTY:_cargo-build_${target_name},CARGO_DEPS_LINKER_LANGUAGES>")
set(deps_link_languages "$<TARGET_GENEX_EVAL:_cargo-build_${target_name},${deps_link_languages_prop}>")
set(target_uses_cxx "$<IN_LIST:CXX,${deps_link_languages}>")
unset(default_linker)
# With the MSVC ABI rustc only supports directly invoking the linker - Invoking cl as the linker driver is not supported.
if(NOT (Rust_CARGO_TARGET_ENV STREQUAL "msvc" OR COR_NO_LINKER_OVERRIDE))
set(default_linker "$<IF:$<BOOL:${target_uses_cxx}>,${CMAKE_CXX_COMPILER},${CMAKE_C_COMPILER}>")
endif()
# Used to set a linker for a specific target-triple.
set(cargo_target_linker_var "CARGO_TARGET_${_CORROSION_RUST_CARGO_TARGET_UPPER}_LINKER")
set(linker "$<IF:${explicit_linker_defined},${explicit_linker_property},${default_linker}>")
set(cargo_target_linker $<$<BOOL:${linker}>:${cargo_target_linker_var}=${linker}>)
if(Rust_CROSSCOMPILING AND (CMAKE_C_COMPILER_TARGET OR CMAKE_CXX_COMPILER_TARGET))
set(linker_target_triple "$<IF:$<BOOL:${target_uses_cxx}>,${CMAKE_CXX_COMPILER_TARGET},${CMAKE_C_COMPILER_TARGET}>")
set(rustflag_linker_arg "-Clink-args=--target=${linker_target_triple}")
set(rustflag_linker_arg "$<${if_not_host_build_condition}:${rustflag_linker_arg}>")
# Skip adding the linker argument, if the linker is explicitly set, since the
# explicit_linker_property will not be set when this function runs.
# Passing this rustflag is necessary for clang.
corrosion_add_target_local_rustflags("${target_name}" "$<$<NOT:${explicit_linker_defined}>:${rustflag_linker_arg}>")
endif()
message(DEBUG "TARGET ${target_name} produces byproducts ${build_byproducts}")
add_custom_target(
_cargo-build_${target_name}
# Build crate
COMMAND
${CMAKE_COMMAND} -E env
"${build_env_variable_genex}"
"${global_rustflags_genex}"
"${cargo_target_linker}"
"${corrosion_cc_rs_flags}"
"${cargo_library_path}"
"CORROSION_BUILD_DIR=${CMAKE_CURRENT_BINARY_DIR}"
"CARGO_BUILD_RUSTC=${rustc_bin}"
"${cargo_bin}"
rustc
${cargo_rustc_filter}
${cargo_target_option}
${_CORROSION_VERBOSE_OUTPUT_FLAG}
${all_features_arg}
${no_default_features_arg}
${features_genex}
--package ${package_name}
${cargo_rustc_crate_types}
--manifest-path "${path_to_toml}"
--target-dir "${cargo_target_dir}"
${cargo_profile}
${flags_genex}
# Any arguments to cargo must be placed before this line
${local_rustflags_delimiter}
${local_rustflags_genex}
# Note: `BYPRODUCTS` may not contain **target specific** generator expressions.
# This means we cannot use `${cargo_build_dir}`, since it currently uses `$<TARGET_PROPERTY>`
# to determine the correct target directory, depending on if the hostbuild target property is
# set or not.
# BYPRODUCTS "${cargo_build_dir}/${build_byproducts}"
# The build is conducted in the directory of the Manifest, so that configuration files such as
# `.cargo/config.toml` or `toolchain.toml` are applied as expected.
WORKING_DIRECTORY "${workspace_toml_dir}"
${cor_uses_terminal}
COMMAND_EXPAND_LISTS
VERBATIM
)
# User exposed custom target, that depends on the internal target.
# Corrosion post build steps are added on the internal target, which
# ensures that they run before any user defined post build steps on this
# target.
add_custom_target(
cargo-build_${target_name}
ALL
)
add_dependencies(cargo-build_${target_name} _cargo-build_${target_name})
# Add custom target before actual build that user defined custom commands (e.g. code generators) can
# use as a hook to do something before the build. This mainly exists to not expose the `_cargo-build` targets.
add_custom_target(cargo-prebuild_${target_name})
add_dependencies(_cargo-build_${target_name} cargo-prebuild_${target_name})
if(NOT TARGET cargo-prebuild)
add_custom_target(cargo-prebuild)
endif()
add_dependencies(cargo-prebuild cargo-prebuild_${target_name})
add_custom_target(
cargo-clean_${target_name}
COMMAND
"${cargo_bin}" clean ${cargo_target_option}
-p ${package_name} --manifest-path "${path_to_toml}"
WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/${build_dir}"
${cor_uses_terminal}
)
if (NOT TARGET cargo-clean)
add_custom_target(cargo-clean)
endif()
add_dependencies(cargo-clean cargo-clean_${target_name})
endfunction()
#[=======================================================================[.md:
ANCHOR: corrosion-import-crate
```cmake
corrosion_import_crate(
MANIFEST_PATH <path/to/cargo.toml>
[ALL_FEATURES]
[NO_DEFAULT_FEATURES]
[NO_STD]
[NO_LINKER_OVERRIDE]
[NO_USES_TERMINAL]
[LOCKED]
[FROZEN]
[PROFILE <cargo-profile>]
[IMPORTED_CRATES <variable-name>]
[CRATE_TYPES <crate_type1> ... <crate_typeN>]
[OVERRIDE_CRATE_TYPE <crate_name>=<crate_type1,crate_type2,...> ...]
[CRATES <crate1> ... <crateN>]
[FEATURES <feature1> ... <featureN>]
[FLAGS <flag1> ... <flagN>]
)
```
* **MANIFEST_PATH**: Path to a [Cargo.toml Manifest] file.
* **ALL_FEATURES**: Equivalent to [--all-features] passed to cargo build
* **NO_DEFAULT_FEATURES**: Equivalent to [--no-default-features] passed to cargo build
* **NO_STD**: Disable linking of standard libraries (required for no_std crates).
* **NO_LINKER_OVERRIDE**: Will let Rust/Cargo determine which linker to use instead of corrosion (when linking is invoked by Rust)
* **NO_USES_TERMINAL**: Don't pass the `USES_TERMINAL` flag when creating the custom CMake targets.
* **LOCKED**: Pass [`--locked`] to cargo build and cargo metadata.
* **FROZEN**: Pass [`--frozen`] to cargo build and cargo metadata.
* **PROFILE**: Specify cargo build profile (`dev`/`release` or a [custom profile]; `bench` and `test` are not supported)
* **IMPORTED_CRATES**: Save the list of imported crates into the variable with the provided name in the current scope.
* **CRATE_TYPES**: Only import the specified crate types. Valid values: `staticlib`, `cdylib`, `bin`.
* **OVERRIDE_CRATE_TYPE**: Override the crate-types of a cargo crate with the given comma-separated values.
Internally uses the `rustc` flag [`--crate-type`] to override the crate-type.
Valid values for the crate types are the library types `staticlib` and `cdylib`.
* **CRATES**: Only import the specified crates from a workspace. Values: Crate names.
* **FEATURES**: Enable the specified features. Equivalent to [--features] passed to `cargo build`.
* **FLAGS**: Arbitrary flags to `cargo build`.
[custom profile]: https://doc.rust-lang.org/cargo/reference/profiles.html#custom-profiles
[--all-features]: https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options
[--no-default-features]: https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options
[--features]: https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options
[`--locked`]: https://doc.rust-lang.org/cargo/commands/cargo.html#manifest-options
[`--frozen`]: https://doc.rust-lang.org/cargo/commands/cargo.html#manifest-options
[`--crate-type`]: https://doc.rust-lang.org/rustc/command-line-arguments.html#--crate-type-a-list-of-types-of-crates-for-the-compiler-to-emit
[Cargo.toml Manifest]: https://doc.rust-lang.org/cargo/appendix/glossary.html#manifest
ANCHOR_END: corrosion-import-crate
#]=======================================================================]
function(corrosion_import_crate)
set(OPTIONS
ALL_FEATURES
NO_DEFAULT_FEATURES
NO_STD
NO_LINKER_OVERRIDE
NO_USES_TERMINAL
LOCKED
FROZEN)
set(ONE_VALUE_KEYWORDS MANIFEST_PATH PROFILE IMPORTED_CRATES)
set(MULTI_VALUE_KEYWORDS CRATE_TYPES CRATES FEATURES FLAGS OVERRIDE_CRATE_TYPE)
cmake_parse_arguments(COR "${OPTIONS}" "${ONE_VALUE_KEYWORDS}" "${MULTI_VALUE_KEYWORDS}" ${ARGN})
list(APPEND CMAKE_MESSAGE_CONTEXT "corrosion_import_crate")
if(DEFINED COR_UNPARSED_ARGUMENTS)
message(AUTHOR_WARNING "Unexpected arguments: " ${COR_UNPARSED_ARGUMENTS}
"\nCorrosion will ignore these unexpected arguments."
)
endif()
if(DEFINED COR_KEYWORDS_MISSING_VALUES)
message(DEBUG "Note: the following keywords passed to corrosion_import_crate had no associated value(s): "
${COR_KEYWORDS_MISSING_VALUES}
)
endif()
if (NOT DEFINED COR_MANIFEST_PATH)
message(FATAL_ERROR "MANIFEST_PATH is a required keyword to corrosion_add_crate")
endif()
_corrosion_option_passthrough_helper(NO_LINKER_OVERRIDE COR no_linker_override)
_corrosion_option_passthrough_helper(LOCKED COR locked)
_corrosion_option_passthrough_helper(FROZEN COR frozen)
_corrosion_arg_passthrough_helper(CRATES COR crate_allowlist)
_corrosion_arg_passthrough_helper(CRATE_TYPES COR crate_types)
if(COR_PROFILE)
if(Rust_VERSION VERSION_LESS 1.57.0)
message(FATAL_ERROR "Selecting custom profiles via `PROFILE` requires at least rust 1.57.0, but you "
"have ${Rust_VERSION}."
)
# The profile name could be part of a Generator expression, so this won't catch all occurences.
# Since it is hard to add an error message for genex, we don't do that here.
elseif("${COR_PROFILE}" STREQUAL "test" OR "${COR_PROFILE}" STREQUAL "bench")
message(FATAL_ERROR "Corrosion does not support building Rust crates with the cargo profiles"
" `test` or `bench`. These profiles add a hash to the output artifact name that we"
" cannot predict. Please consider using a custom cargo profile which inherits from the"
" built-in profile instead."
)
endif()
endif()
# intended to be used with foreach(... ZIP_LISTS ...), meaning
# that the crate_types at index i of `override_crate_type_types_list` are
# for the package_name at index i of `override_crate_type_package_name_list`.
# It would really be nice if CMake had structs or dicts.
unset(override_crate_type_package_name_list)
unset(override_crate_type_types_list)
unset(OVERRIDE_CRATE_TYPE_ARGS)
if(DEFINED COR_OVERRIDE_CRATE_TYPE)
string(JOIN " " usage_help
"Each argument to OVERRIDE_CRATE_TYPE must be of the form `<package_name>=<crate_type(s)>."
"The package_name must be a valid cargo package name and the crate_type must be "
"a comma-seperated list with valid values being `staticlib`, `cdylib` and `bin`"
)
foreach(entry IN LISTS COR_OVERRIDE_CRATE_TYPE)
string(REPLACE "=" ";" key_val_list ${entry})