-
Notifications
You must be signed in to change notification settings - Fork 440
/
rust.bzl
1364 lines (1170 loc) · 46.2 KB
/
rust.bzl
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
# Copyright 2015 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# buildifier: disable=module-docstring
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//rust/private:common.bzl", "rust_common")
load("//rust/private:rustc.bzl", "rustc_compile_action")
load(
"//rust/private:utils.bzl",
"can_build_metadata",
"compute_crate_name",
"dedent",
"determine_output_hash",
"expand_dict_value_locations",
"find_toolchain",
"get_import_macro_deps",
"transform_deps",
)
# TODO(marco): Separate each rule into its own file.
def _assert_no_deprecated_attributes(_ctx):
"""Forces a failure if any deprecated attributes were specified
Args:
_ctx (ctx): The current rule's context object
"""
pass
def _assert_correct_dep_mapping(ctx):
"""Forces a failure if proc_macro_deps and deps are mixed inappropriately
Args:
ctx (ctx): The current rule's context object
"""
for dep in ctx.attr.deps:
if rust_common.crate_info in dep:
if dep[rust_common.crate_info].type == "proc-macro":
fail(
"{} listed {} in its deps, but it is a proc-macro. It should instead be in the bazel property proc_macro_deps.".format(
ctx.label,
dep.label,
),
)
for dep in ctx.attr.proc_macro_deps:
type = dep[rust_common.crate_info].type
if type != "proc-macro":
fail(
"{} listed {} in its proc_macro_deps, but it is not proc-macro, it is a {}. It should probably instead be listed in deps.".format(
ctx.label,
dep.label,
type,
),
)
def _determine_lib_name(name, crate_type, toolchain, lib_hash = None):
"""See https://github.com/bazelbuild/rules_rust/issues/405
Args:
name (str): The name of the current target
crate_type (str): The `crate_type`
toolchain (rust_toolchain): The current `rust_toolchain`
lib_hash (str, optional): The hashed crate root path
Returns:
str: A unique library name
"""
extension = None
prefix = ""
if crate_type in ("dylib", "cdylib", "proc-macro"):
extension = toolchain.dylib_ext
elif crate_type == "staticlib":
extension = toolchain.staticlib_ext
elif crate_type in ("lib", "rlib"):
# All platforms produce 'rlib' here
extension = ".rlib"
prefix = "lib"
elif crate_type == "bin":
fail("crate_type of 'bin' was detected in a rust_library. Please compile " +
"this crate as a rust_binary instead.")
if not extension:
fail(("Unknown crate_type: {}. If this is a cargo-supported crate type, " +
"please file an issue!").format(crate_type))
prefix = "lib"
if (toolchain.target_triple.find("windows") != -1) and crate_type not in ("lib", "rlib"):
prefix = ""
if toolchain.target_arch == "wasm32" and crate_type == "cdylib":
prefix = ""
return "{prefix}{name}{lib_hash}{extension}".format(
prefix = prefix,
name = name,
lib_hash = "-" + lib_hash if lib_hash else "",
extension = extension,
)
def get_edition(attr, toolchain, label):
"""Returns the Rust edition from either the current rule's attirbutes or the current `rust_toolchain`
Args:
attr (struct): The current rule's attributes
toolchain (rust_toolchain): The `rust_toolchain` for the current target
label (Label): The label of the target being built
Returns:
str: The target Rust edition
"""
if getattr(attr, "edition"):
return attr.edition
elif not toolchain.default_edition:
fail("Attribute `edition` is required for {}.".format(label))
else:
return toolchain.default_edition
def _transform_sources(ctx, srcs, crate_root):
"""Creates symlinks of the source files if needed.
Rustc assumes that the source files are located next to the crate root.
In case of a mix between generated and non-generated source files, this
we violate this assumption, as part of the sources will be located under
bazel-out/... . In order to allow for targets that contain both generated
and non-generated source files, we generate symlinks for all non-generated
files.
Args:
ctx (struct): The current rule's context.
srcs (List[File]): The sources listed in the `srcs` attribute
crate_root (File): The file specified in the `crate_root` attribute,
if it exists, otherwise None
Returns:
Tuple(List[File], File): The transformed srcs and crate_root
"""
has_generated_sources = len([src for src in srcs if not src.is_source]) > 0
if not has_generated_sources:
return srcs, crate_root
generated_sources = []
generated_root = crate_root
package_root = paths.dirname(ctx.build_file_path)
if crate_root and (crate_root.is_source or crate_root.root.path != ctx.bin_dir.path):
generated_root = ctx.actions.declare_file(paths.relativize(crate_root.short_path, package_root))
ctx.actions.symlink(
output = generated_root,
target_file = crate_root,
progress_message = "Creating symlink to source file: {}".format(crate_root.path),
)
if generated_root:
generated_sources.append(generated_root)
for src in srcs:
# We took care of the crate root above.
if src == crate_root:
continue
if src.is_source or src.root.path != ctx.bin_dir.path:
src_symlink = ctx.actions.declare_file(paths.relativize(src.short_path, package_root))
ctx.actions.symlink(
output = src_symlink,
target_file = src,
progress_message = "Creating symlink to source file: {}".format(src.path),
)
generated_sources.append(src_symlink)
else:
generated_sources.append(src)
return generated_sources, generated_root
def crate_root_src(name, srcs, crate_type):
"""Determines the source file for the crate root, should it not be specified in `attr.crate_root`.
Args:
name (str): The name of the target.
srcs (list): A list of all sources for the target Crate.
crate_type (str): The type of this crate ("bin", "lib", "rlib", "cdylib", etc).
Returns:
File: The root File object for a given crate. See the following links for more details:
- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#library
- https://doc.rust-lang.org/cargo/reference/cargo-targets.html#binaries
"""
default_crate_root_filename = "main.rs" if crate_type == "bin" else "lib.rs"
crate_root = (
(srcs[0] if len(srcs) == 1 else None) or
_shortest_src_with_basename(srcs, default_crate_root_filename) or
_shortest_src_with_basename(srcs, name + ".rs")
)
if not crate_root:
file_names = [default_crate_root_filename, name + ".rs"]
fail("No {} source file found.".format(" or ".join(file_names)), "srcs")
return crate_root
def _shortest_src_with_basename(srcs, basename):
"""Finds the shortest among the paths in srcs that match the desired basename.
Args:
srcs (list): A list of File objects
basename (str): The target basename to match against.
Returns:
File: The File object with the shortest path that matches `basename`
"""
shortest = None
for f in srcs:
if f.basename == basename:
if not shortest or len(f.dirname) < len(shortest.dirname):
shortest = f
return shortest
def _rust_library_impl(ctx):
"""The implementation of the `rust_library` rule.
This rule provides CcInfo, so it can be used everywhere Bazel
expects rules_cc, but care must be taken to have the correct
dependencies on an allocator and std implemetation as needed.
Args:
ctx (ctx): The rule's context object
Returns:
list: A list of providers.
"""
return _rust_library_common(ctx, "rlib")
def _rust_static_library_impl(ctx):
"""The implementation of the `rust_static_library` rule.
This rule provides CcInfo, so it can be used everywhere Bazel
expects rules_cc.
Args:
ctx (ctx): The rule's context object
Returns:
list: A list of providers.
"""
return _rust_library_common(ctx, "staticlib")
def _rust_shared_library_impl(ctx):
"""The implementation of the `rust_shared_library` rule.
This rule provides CcInfo, so it can be used everywhere Bazel
expects rules_cc.
On Windows, a PDB file containing debugging information is available under
the key `pdb_file` in `OutputGroupInfo`. Similarly on macOS, a dSYM folder
is available under the key `dsym_folder` in `OutputGroupInfo`.
Args:
ctx (ctx): The rule's context object
Returns:
list: A list of providers.
"""
return _rust_library_common(ctx, "cdylib")
def _rust_proc_macro_impl(ctx):
"""The implementation of the `rust_proc_macro` rule.
Args:
ctx (ctx): The rule's context object
Returns:
list: A list of providers.
"""
return _rust_library_common(ctx, "proc-macro")
def _rust_library_common(ctx, crate_type):
"""The common implementation of the library-like rules.
Args:
ctx (ctx): The rule's context object
crate_type (String): one of lib|rlib|dylib|staticlib|cdylib|proc-macro
Returns:
list: A list of providers. See `rustc_compile_action`
"""
srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
if not crate_root:
crate_root = crate_root_src(ctx.attr.name, srcs, "lib")
_assert_no_deprecated_attributes(ctx)
_assert_correct_dep_mapping(ctx)
toolchain = find_toolchain(ctx)
# Determine unique hash for this rlib.
# Note that we don't include a hash for `cdylib` and `staticlib` since they are meant to be consumed externally
# and having a deterministic name is important since it ends up embedded in the executable. This is problematic
# when one needs to include the library with a specific filename into a larger application.
# (see https://github.com/bazelbuild/rules_rust/issues/405#issuecomment-993089889 for more details)
if crate_type in ["cdylib", "staticlib"]:
output_hash = None
else:
output_hash = determine_output_hash(crate_root, ctx.label)
crate_name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name)
rust_lib_name = _determine_lib_name(
crate_name,
crate_type,
toolchain,
output_hash,
)
rust_lib = ctx.actions.declare_file(rust_lib_name)
rust_metadata = None
if can_build_metadata(toolchain, ctx, crate_type) and not ctx.attr.disable_pipelining:
rust_metadata = ctx.actions.declare_file(
paths.replace_extension(rust_lib_name, ".rmeta"),
sibling = rust_lib,
)
deps = transform_deps(ctx.attr.deps)
proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
return rustc_compile_action(
ctx = ctx,
attr = ctx.attr,
toolchain = toolchain,
crate_info = rust_common.create_crate_info(
name = crate_name,
type = crate_type,
root = crate_root,
srcs = depset(srcs),
deps = depset(deps),
proc_macro_deps = depset(proc_macro_deps),
aliases = ctx.attr.aliases,
output = rust_lib,
metadata = rust_metadata,
edition = get_edition(ctx.attr, toolchain, ctx.label),
rustc_env = ctx.attr.rustc_env,
rustc_env_files = ctx.files.rustc_env_files,
is_test = False,
compile_data = depset(ctx.files.compile_data),
owner = ctx.label,
),
output_hash = output_hash,
)
def _rust_binary_impl(ctx):
"""The implementation of the `rust_binary` rule
Args:
ctx (ctx): The rule's context object
Returns:
list: A list of providers. See `rustc_compile_action`
"""
toolchain = find_toolchain(ctx)
crate_name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name)
_assert_correct_dep_mapping(ctx)
output = ctx.actions.declare_file(ctx.label.name + toolchain.binary_ext)
deps = transform_deps(ctx.attr.deps)
proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
if not crate_root:
crate_root = crate_root_src(ctx.attr.name, srcs, ctx.attr.crate_type)
return rustc_compile_action(
ctx = ctx,
attr = ctx.attr,
toolchain = toolchain,
crate_info = rust_common.create_crate_info(
name = crate_name,
type = ctx.attr.crate_type,
root = crate_root,
srcs = depset(srcs),
deps = depset(deps),
proc_macro_deps = depset(proc_macro_deps),
aliases = ctx.attr.aliases,
output = output,
edition = get_edition(ctx.attr, toolchain, ctx.label),
rustc_env = ctx.attr.rustc_env,
rustc_env_files = ctx.files.rustc_env_files,
is_test = False,
compile_data = depset(ctx.files.compile_data),
owner = ctx.label,
),
)
def _rust_test_impl(ctx):
"""The implementation of the `rust_test` rule.
Args:
ctx (ctx): The ctx object for the current target.
Returns:
list: The list of providers. See `rustc_compile_action`
"""
_assert_no_deprecated_attributes(ctx)
_assert_correct_dep_mapping(ctx)
toolchain = find_toolchain(ctx)
srcs, crate_root = _transform_sources(ctx, ctx.files.srcs, getattr(ctx.file, "crate_root", None))
crate_type = "bin"
deps = transform_deps(ctx.attr.deps)
proc_macro_deps = transform_deps(ctx.attr.proc_macro_deps + get_import_macro_deps(ctx))
if ctx.attr.crate:
# Target is building the crate in `test` config
crate = ctx.attr.crate[rust_common.crate_info] if rust_common.crate_info in ctx.attr.crate else ctx.attr.crate[rust_common.test_crate_info].crate
output_hash = determine_output_hash(crate.root, ctx.label)
output = ctx.actions.declare_file(
"test-%s/%s%s" % (
output_hash,
ctx.label.name,
toolchain.binary_ext,
),
)
# Optionally join compile data
if crate.compile_data:
compile_data = depset(ctx.files.compile_data, transitive = [crate.compile_data])
else:
compile_data = depset(ctx.files.compile_data)
rustc_env_files = ctx.files.rustc_env_files + crate.rustc_env_files
rustc_env = dict(crate.rustc_env)
rustc_env.update(**ctx.attr.rustc_env)
# Build the test binary using the dependency's srcs.
crate_info = rust_common.create_crate_info(
name = crate.name,
type = crate_type,
root = crate.root,
srcs = depset(srcs, transitive = [crate.srcs]),
deps = depset(deps, transitive = [crate.deps]),
proc_macro_deps = depset(proc_macro_deps, transitive = [crate.proc_macro_deps]),
aliases = ctx.attr.aliases,
output = output,
edition = crate.edition,
rustc_env = rustc_env,
rustc_env_files = rustc_env_files,
is_test = True,
compile_data = compile_data,
wrapped_crate_type = crate.type,
owner = ctx.label,
)
else:
if not crate_root:
crate_root_type = "lib" if ctx.attr.use_libtest_harness else "bin"
crate_root = crate_root_src(ctx.attr.name, ctx.files.srcs, crate_root_type)
output_hash = determine_output_hash(crate_root, ctx.label)
output = ctx.actions.declare_file(
"test-%s/%s%s" % (
output_hash,
ctx.label.name,
toolchain.binary_ext,
),
)
# Target is a standalone crate. Build the test binary as its own crate.
crate_info = rust_common.create_crate_info(
name = compute_crate_name(ctx.workspace_name, ctx.label, toolchain, ctx.attr.crate_name),
type = crate_type,
root = crate_root,
srcs = depset(srcs),
deps = depset(deps),
proc_macro_deps = depset(proc_macro_deps),
aliases = ctx.attr.aliases,
output = output,
edition = get_edition(ctx.attr, toolchain, ctx.label),
rustc_env = ctx.attr.rustc_env,
rustc_env_files = ctx.files.rustc_env_files,
is_test = True,
compile_data = depset(ctx.files.compile_data),
owner = ctx.label,
)
providers = rustc_compile_action(
ctx = ctx,
attr = ctx.attr,
toolchain = toolchain,
crate_info = crate_info,
rust_flags = ["--test"] if ctx.attr.use_libtest_harness else ["--cfg", "test"],
)
data = getattr(ctx.attr, "data", [])
env = expand_dict_value_locations(
ctx,
getattr(ctx.attr, "env", {}),
data,
)
if toolchain.llvm_cov and ctx.configuration.coverage_enabled:
if not toolchain.llvm_profdata:
fail("toolchain.llvm_profdata is required if toolchain.llvm_cov is set.")
env["RUST_LLVM_COV"] = toolchain.llvm_cov.path
env["RUST_LLVM_PROFDATA"] = toolchain.llvm_profdata.path
providers.append(testing.TestEnvironment(env))
return providers
def _stamp_attribute(default_value):
return attr.int(
doc = dedent("""\
Whether to encode build information into the `Rustc` action. Possible values:
- `stamp = 1`: Always stamp the build information into the `Rustc` action, even in \
[--nostamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) builds. \
This setting should be avoided, since it potentially kills remote caching for the target and \
any downstream actions that depend on it.
- `stamp = 0`: Always replace build information by constant values. This gives good build result caching.
- `stamp = -1`: Embedding of build information is controlled by the \
[--[no]stamp](https://docs.bazel.build/versions/main/user-manual.html#flag--stamp) flag.
Stamped targets are not rebuilt unless their dependencies change.
For example if a `rust_library` is stamped, and a `rust_binary` depends on that library, the stamped
library won't be rebuilt when we change sources of the `rust_binary`. This is different from how
[`cc_library.linkstamps`](https://docs.bazel.build/versions/main/be/c-cpp.html#cc_library.linkstamp)
behaves.
"""),
default = default_value,
values = [1, 0, -1],
)
_common_attrs = {
"aliases": attr.label_keyed_string_dict(
doc = dedent("""\
Remap crates to a new name or moniker for linkage to this target
These are other `rust_library` targets and will be presented as the new name given.
"""),
),
"compile_data": attr.label_list(
doc = dedent("""\
List of files used by this rule at compile time.
This attribute can be used to specify any data files that are embedded into
the library, such as via the
[`include_str!`](https://doc.rust-lang.org/std/macro.include_str!.html)
macro.
"""),
allow_files = True,
),
"crate_features": attr.string_list(
doc = dedent("""\
List of features to enable for this crate.
Features are defined in the code using the `#[cfg(feature = "foo")]`
configuration option. The features listed here will be passed to `rustc`
with `--cfg feature="${feature_name}"` flags.
"""),
),
"crate_name": attr.string(
doc = dedent("""\
Crate name to use for this target.
This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores.
Defaults to the target name, with any hyphens replaced by underscores.
"""),
),
"crate_root": attr.label(
doc = dedent("""\
The file that will be passed to `rustc` to be used for building this crate.
If `crate_root` is not set, then this rule will look for a `lib.rs` file (or `main.rs` for rust_binary)
or the single file in `srcs` if `srcs` contains only one file.
"""),
allow_single_file = [".rs"],
),
"data": attr.label_list(
doc = dedent("""\
List of files used by this rule at compile time and runtime.
If including data at compile time with include_str!() and similar,
prefer `compile_data` over `data`, to prevent the data also being included
in the runfiles.
"""),
allow_files = True,
),
"deps": attr.label_list(
doc = dedent("""\
List of other libraries to be linked to this library target.
These can be either other `rust_library` targets or `cc_library` targets if
linking a native library.
"""),
),
"edition": attr.string(
doc = "The rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.",
),
# Previously `proc_macro_deps` were a part of `deps`, and then proc_macro_host_transition was
# used into cfg="host" using `@local_config_platform//:host`.
# This fails for remote execution, which needs cfg="exec", and there isn't anything like
# `@local_config_platform//:exec` exposed.
"proc_macro_deps": attr.label_list(
doc = dedent("""\
List of `rust_library` targets with kind `proc-macro` used to help build this library target.
"""),
cfg = "exec",
providers = [rust_common.crate_info],
),
"rustc_env": attr.string_dict(
doc = dedent("""\
Dictionary of additional `"key": "value"` environment variables to set for rustc.
rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the
location of a generated file or external tool. Cargo build scripts that wish to
expand locations should use cargo_build_script()'s build_script_env argument instead,
as build scripts are run in a different environment - see cargo_build_script()'s
documentation for more.
"""),
),
"rustc_env_files": attr.label_list(
doc = dedent("""\
Files containing additional environment variables to set for rustc.
These files should contain a single variable per line, of format
`NAME=value`, and newlines may be included in a value by ending a
line with a trailing back-slash (`\\\\`).
The order that these files will be processed is unspecified, so
multiple definitions of a particular variable are discouraged.
Note that the variables here are subject to
[workspace status](https://docs.bazel.build/versions/main/user-manual.html#workspace_status)
stamping should the `stamp` attribute be enabled. Stamp variables
should be wrapped in brackets in order to be resolved. E.g.
`NAME={WORKSPACE_STATUS_VARIABLE}`.
"""),
allow_files = True,
),
"rustc_flags": attr.string_list(
doc = dedent("""\
List of compiler flags passed to `rustc`.
These strings are subject to Make variable expansion for predefined
source/output path variables like `$location`, `$execpath`, and
`$rootpath`. This expansion is useful if you wish to pass a generated
file of arguments to rustc: `@$(location //package:target)`.
"""),
),
# TODO(stardoc): How do we provide additional documentation to an inherited attribute?
# "name": attr.string(
# doc = "This name will also be used as the name of the crate built by this rule.",
# `),
"srcs": attr.label_list(
doc = dedent("""\
List of Rust `.rs` source files used to build the library.
If `srcs` contains more than one file, then there must be a file either
named `lib.rs`. Otherwise, `crate_root` must be set to the source file that
is the root of the crate to be passed to rustc to build this crate.
"""),
allow_files = [".rs"],
),
"stamp": _stamp_attribute(default_value = 0),
"version": attr.string(
doc = "A version to inject in the cargo environment variable.",
default = "0.0.0",
),
"_cc_toolchain": attr.label(
doc = (
"In order to use find_cc_toolchain, your rule has to depend " +
"on C++ toolchain. See `@rules_cc//cc:find_cc_toolchain.bzl` " +
"docs for details."
),
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
"_collect_cc_coverage": attr.label(
default = Label("//util:collect_coverage"),
executable = True,
cfg = "exec",
),
"_error_format": attr.label(
default = Label("//:error_format"),
),
"_extra_exec_rustc_flag": attr.label(
default = Label("//:extra_exec_rustc_flag"),
),
"_extra_exec_rustc_flags": attr.label(
default = Label("//:extra_exec_rustc_flags"),
),
"_extra_rustc_flag": attr.label(
default = Label("//:extra_rustc_flag"),
),
"_extra_rustc_flags": attr.label(
default = Label("//:extra_rustc_flags"),
),
"_import_macro_dep": attr.label(
default = Label("//util/import"),
cfg = "exec",
),
"_is_proc_macro_dep": attr.label(
default = Label("//:is_proc_macro_dep"),
),
"_is_proc_macro_dep_enabled": attr.label(
default = Label("//:is_proc_macro_dep_enabled"),
),
"_process_wrapper": attr.label(
doc = "A process wrapper for running rustc on all platforms.",
default = Label("//util/process_wrapper"),
executable = True,
allow_single_file = True,
cfg = "exec",
),
"_stamp_flag": attr.label(
doc = "A setting used to determine whether or not the `--stamp` flag is enabled",
default = Label("//rust/private:stamp"),
),
}
_experimental_use_cc_common_link_attrs = {
"experimental_use_cc_common_link": attr.int(
doc = (
"Whether to use cc_common.link to link rust binaries. " +
"Possible values: [-1, 0, 1]. " +
"-1 means use the value of the toolchain.experimental_use_cc_common_link " +
"boolean build setting to determine. " +
"0 means do not use cc_common.link (use rustc instead). " +
"1 means use cc_common.link."
),
values = [-1, 0, 1],
default = -1,
),
}
_rust_test_attrs = dict({
"crate": attr.label(
mandatory = False,
doc = dedent("""\
Target inline tests declared in the given crate
These tests are typically those that would be held out under
`#[cfg(test)]` declarations.
"""),
),
"env": attr.string_dict(
mandatory = False,
doc = dedent("""\
Specifies additional environment variables to set when the test is executed by bazel test.
Values are subject to `$(rootpath)`, `$(execpath)`, location, and
["Make variable"](https://docs.bazel.build/versions/master/be/make-variables.html) substitution.
Execpath returns absolute path, and in order to be able to construct the absolute path we
need to wrap the test binary in a launcher. Using a launcher comes with complications, such as
more complicated debugger attachment.
"""),
),
"use_libtest_harness": attr.bool(
mandatory = False,
default = True,
doc = dedent("""\
Whether to use `libtest`. For targets using this flag, individual tests can be run by using the
[--test_arg](https://docs.bazel.build/versions/4.0.0/command-line-reference.html#flag--test_arg) flag.
E.g. `bazel test //src:rust_test --test_arg=foo::test::test_fn`.
"""),
),
"_grep_includes": attr.label(
allow_single_file = True,
cfg = "exec",
default = Label("@bazel_tools//tools/cpp:grep-includes"),
executable = True,
),
}.items() + _experimental_use_cc_common_link_attrs.items())
_common_providers = [
rust_common.crate_info,
rust_common.dep_info,
DefaultInfo,
]
rust_library = rule(
implementation = _rust_library_impl,
provides = _common_providers,
attrs = dict(_common_attrs.items() + {
"disable_pipelining": attr.bool(
default = False,
doc = dedent("""\
Disables pipelining for this rule if it is globally enabled.
This will cause this rule to not produce a `.rmeta` file and all the dependent
crates will instead use the `.rlib` file.
"""),
),
}.items()),
fragments = ["cpp"],
host_fragments = ["cpp"],
toolchains = [
str(Label("//rust:toolchain_type")),
"@bazel_tools//tools/cpp:toolchain_type",
],
incompatible_use_toolchain_transition = True,
doc = dedent("""\
Builds a Rust library crate.
Example:
Suppose you have the following directory structure for a simple Rust library crate:
```output
[workspace]/
WORKSPACE
hello_lib/
BUILD
src/
greeter.rs
lib.rs
```
`hello_lib/src/greeter.rs`:
```rust
pub struct Greeter {
greeting: String,
}
impl Greeter {
pub fn new(greeting: &str) -> Greeter {
Greeter { greeting: greeting.to_string(), }
}
pub fn greet(&self, thing: &str) {
println!("{} {}", &self.greeting, thing);
}
}
```
`hello_lib/src/lib.rs`:
```rust
pub mod greeter;
```
`hello_lib/BUILD`:
```python
package(default_visibility = ["//visibility:public"])
load("@rules_rust//rust:defs.bzl", "rust_library")
rust_library(
name = "hello_lib",
srcs = [
"src/greeter.rs",
"src/lib.rs",
],
)
```
Build the library:
```output
$ bazel build //hello_lib
INFO: Found 1 target...
Target //examples/rust/hello_lib:hello_lib up-to-date:
bazel-bin/examples/rust/hello_lib/libhello_lib.rlib
INFO: Elapsed time: 1.245s, Critical Path: 1.01s
```
"""),
)
rust_static_library = rule(
implementation = _rust_static_library_impl,
attrs = dict(_common_attrs.items()),
fragments = ["cpp"],
host_fragments = ["cpp"],
toolchains = [
str(Label("//rust:toolchain_type")),
"@bazel_tools//tools/cpp:toolchain_type",
],
incompatible_use_toolchain_transition = True,
doc = dedent("""\
Builds a Rust static library.
This static library will contain all transitively reachable crates and native objects.
It is meant to be used when producing an artifact that is then consumed by some other build system
(for example to produce an archive that Python program links against).
This rule provides CcInfo, so it can be used everywhere Bazel expects `rules_cc`.
When building the whole binary in Bazel, use `rust_library` instead.
"""),
)
rust_shared_library = rule(
implementation = _rust_shared_library_impl,
attrs = dict(_common_attrs.items()),
fragments = ["cpp"],
host_fragments = ["cpp"],
toolchains = [
str(Label("//rust:toolchain_type")),
"@bazel_tools//tools/cpp:toolchain_type",
],
incompatible_use_toolchain_transition = True,
doc = dedent("""\
Builds a Rust shared library.
This shared library will contain all transitively reachable crates and native objects.
It is meant to be used when producing an artifact that is then consumed by some other build system
(for example to produce a shared library that Python program links against).
This rule provides CcInfo, so it can be used everywhere Bazel expects `rules_cc`.
When building the whole binary in Bazel, use `rust_library` instead.
"""),
)
def _proc_macro_dep_transition_impl(settings, _attr):
if settings["//:is_proc_macro_dep_enabled"]:
return {"//:is_proc_macro_dep": True}
else:
return []
_proc_macro_dep_transition = transition(
inputs = ["//:is_proc_macro_dep_enabled"],
outputs = ["//:is_proc_macro_dep"],
implementation = _proc_macro_dep_transition_impl,
)
rust_proc_macro = rule(
implementation = _rust_proc_macro_impl,
provides = _common_providers,
# Start by copying the common attributes, then override the `deps` attribute
# to apply `_proc_macro_dep_transition`. To add this transition we additionally
# need to declare `_allowlist_function_transition`, see
# https://docs.bazel.build/versions/main/skylark/config.html#user-defined-transitions.
attrs = dict(
_common_attrs.items(),
_allowlist_function_transition = attr.label(default = Label("//tools/allowlists/function_transition_allowlist")),
deps = attr.label_list(
doc = dedent("""\
List of other libraries to be linked to this library target.
These can be either other `rust_library` targets or `cc_library` targets if
linking a native library.
"""),
cfg = _proc_macro_dep_transition,
),
),
fragments = ["cpp"],
host_fragments = ["cpp"],
toolchains = [
str(Label("//rust:toolchain_type")),
"@bazel_tools//tools/cpp:toolchain_type",
],
incompatible_use_toolchain_transition = True,
doc = dedent("""\
Builds a Rust proc-macro crate.
"""),
)
_rust_binary_attrs = dict({
"crate_type": attr.string(
doc = dedent("""\
Crate type that will be passed to `rustc` to be used for building this crate.
This option is a temporary workaround and should be used only when building
for WebAssembly targets (//rust/platform:wasi and //rust/platform:wasm).
"""),
default = "bin",
),
"linker_script": attr.label(
doc = dedent("""\
Link script to forward into linker via rustc options.
"""),
cfg = "exec",
allow_single_file = True,
),
"out_binary": attr.bool(
doc = (
"Force a target, regardless of it's `crate_type`, to always mark the " +
"file as executable. This attribute is only used to support wasm targets but is " +
"expected to be removed following a resolution to https://github.com/bazelbuild/rules_rust/issues/771."
),
default = False,
),
"stamp": _stamp_attribute(default_value = -1),
"_grep_includes": attr.label(
allow_single_file = True,
cfg = "exec",
default = Label("@bazel_tools//tools/cpp:grep-includes"),
executable = True,
),
}.items() + _experimental_use_cc_common_link_attrs.items())
rust_binary = rule(
implementation = _rust_binary_impl,
provides = _common_providers,