-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Build.zig
1862 lines (1686 loc) · 64.6 KB
/
Build.zig
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
const std = @import("std.zig");
const builtin = @import("builtin");
const io = std.io;
const fs = std.fs;
const mem = std.mem;
const debug = std.debug;
const panic = std.debug.panic;
const assert = debug.assert;
const log = std.log;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const Allocator = mem.Allocator;
const process = std.process;
const EnvMap = std.process.EnvMap;
const fmt_lib = std.fmt;
const File = std.fs.File;
const CrossTarget = std.zig.CrossTarget;
const NativeTargetInfo = std.zig.system.NativeTargetInfo;
const Sha256 = std.crypto.hash.sha2.Sha256;
const Build = @This();
pub const Cache = @import("Build/Cache.zig");
/// deprecated: use `Step.Compile`.
pub const LibExeObjStep = Step.Compile;
/// deprecated: use `Build`.
pub const Builder = Build;
/// deprecated: use `Step.InstallDir.Options`
pub const InstallDirectoryOptions = Step.InstallDir.Options;
pub const Step = @import("Build/Step.zig");
/// deprecated: use `Step.CheckFile`.
pub const CheckFileStep = @import("Build/Step/CheckFile.zig");
/// deprecated: use `Step.CheckObject`.
pub const CheckObjectStep = @import("Build/Step/CheckObject.zig");
/// deprecated: use `Step.ConfigHeader`.
pub const ConfigHeaderStep = @import("Build/Step/ConfigHeader.zig");
/// deprecated: use `Step.Fmt`.
pub const FmtStep = @import("Build/Step/Fmt.zig");
/// deprecated: use `Step.InstallArtifact`.
pub const InstallArtifactStep = @import("Build/Step/InstallArtifact.zig");
/// deprecated: use `Step.InstallDir`.
pub const InstallDirStep = @import("Build/Step/InstallDir.zig");
/// deprecated: use `Step.InstallFile`.
pub const InstallFileStep = @import("Build/Step/InstallFile.zig");
/// deprecated: use `Step.ObjCopy`.
pub const ObjCopyStep = @import("Build/Step/ObjCopy.zig");
/// deprecated: use `Step.Compile`.
pub const CompileStep = @import("Build/Step/Compile.zig");
/// deprecated: use `Step.Options`.
pub const OptionsStep = @import("Build/Step/Options.zig");
/// deprecated: use `Step.RemoveDir`.
pub const RemoveDirStep = @import("Build/Step/RemoveDir.zig");
/// deprecated: use `Step.Run`.
pub const RunStep = @import("Build/Step/Run.zig");
/// deprecated: use `Step.TranslateC`.
pub const TranslateCStep = @import("Build/Step/TranslateC.zig");
/// deprecated: use `Step.WriteFile`.
pub const WriteFileStep = @import("Build/Step/WriteFile.zig");
install_tls: TopLevelStep,
uninstall_tls: TopLevelStep,
allocator: Allocator,
user_input_options: UserInputOptionsMap,
available_options_map: AvailableOptionsMap,
available_options_list: ArrayList(AvailableOption),
verbose: bool,
verbose_link: bool,
verbose_cc: bool,
verbose_air: bool,
verbose_llvm_ir: ?[]const u8,
verbose_llvm_bc: ?[]const u8,
verbose_cimport: bool,
verbose_llvm_cpu_features: bool,
reference_trace: ?u32 = null,
invalid_user_input: bool,
zig_exe: [:0]const u8,
default_step: *Step,
env_map: *EnvMap,
top_level_steps: std.StringArrayHashMapUnmanaged(*TopLevelStep),
install_prefix: []const u8,
dest_dir: ?[]const u8,
lib_dir: []const u8,
exe_dir: []const u8,
h_dir: []const u8,
install_path: []const u8,
sysroot: ?[]const u8 = null,
search_prefixes: ArrayList([]const u8),
libc_file: ?[]const u8 = null,
installed_files: ArrayList(InstalledFile),
/// Path to the directory containing build.zig.
build_root: Cache.Directory,
cache_root: Cache.Directory,
global_cache_root: Cache.Directory,
cache: *Cache,
/// If non-null, overrides the default zig lib dir.
zig_lib_dir: ?[]const u8,
vcpkg_root: VcpkgRoot = .unattempted,
pkg_config_pkg_list: ?(PkgConfigError![]const PkgConfigPkg) = null,
args: ?[][]const u8 = null,
debug_log_scopes: []const []const u8 = &.{},
debug_compile_errors: bool = false,
debug_pkg_config: bool = false,
/// Experimental. Use system Darling installation to run cross compiled macOS build artifacts.
enable_darling: bool = false,
/// Use system QEMU installation to run cross compiled foreign architecture build artifacts.
enable_qemu: bool = false,
/// Darwin. Use Rosetta to run x86_64 macOS build artifacts on arm64 macOS.
enable_rosetta: bool = false,
/// Use system Wasmtime installation to run cross compiled wasm/wasi build artifacts.
enable_wasmtime: bool = false,
/// Use system Wine installation to run cross compiled Windows build artifacts.
enable_wine: bool = false,
/// After following the steps in https://github.com/ziglang/zig/wiki/Updating-libc#glibc,
/// this will be the directory $glibc-build-dir/install/glibcs
/// Given the example of the aarch64 target, this is the directory
/// that contains the path `aarch64-linux-gnu/lib/ld-linux-aarch64.so.1`.
glibc_runtimes_dir: ?[]const u8 = null,
/// Information about the native target. Computed before build() is invoked.
host: NativeTargetInfo,
dep_prefix: []const u8 = "",
modules: std.StringArrayHashMap(*Module),
/// A map from build root dirs to the corresponding `*Dependency`. This is shared with all child
/// `Build`s.
initialized_deps: *std.StringHashMap(*Dependency),
pub const ExecError = error{
ReadFailure,
ExitCodeFailure,
ProcessTerminated,
ExecNotSupported,
} || std.ChildProcess.SpawnError;
pub const PkgConfigError = error{
PkgConfigCrashed,
PkgConfigFailed,
PkgConfigNotInstalled,
PkgConfigInvalidOutput,
};
pub const PkgConfigPkg = struct {
name: []const u8,
desc: []const u8,
};
pub const CStd = enum {
C89,
C99,
C11,
};
const UserInputOptionsMap = StringHashMap(UserInputOption);
const AvailableOptionsMap = StringHashMap(AvailableOption);
const AvailableOption = struct {
name: []const u8,
type_id: TypeId,
description: []const u8,
/// If the `type_id` is `enum` this provides the list of enum options
enum_options: ?[]const []const u8,
};
const UserInputOption = struct {
name: []const u8,
value: UserValue,
used: bool,
};
const UserValue = union(enum) {
flag: void,
scalar: []const u8,
list: ArrayList([]const u8),
map: StringHashMap(*const UserValue),
};
const TypeId = enum {
bool,
int,
float,
@"enum",
string,
list,
build_id,
};
const TopLevelStep = struct {
pub const base_id = .top_level;
step: Step,
description: []const u8,
};
pub const DirList = struct {
lib_dir: ?[]const u8 = null,
exe_dir: ?[]const u8 = null,
include_dir: ?[]const u8 = null,
};
pub fn create(
allocator: Allocator,
zig_exe: [:0]const u8,
build_root: Cache.Directory,
cache_root: Cache.Directory,
global_cache_root: Cache.Directory,
host: NativeTargetInfo,
cache: *Cache,
) !*Build {
const env_map = try allocator.create(EnvMap);
env_map.* = try process.getEnvMap(allocator);
const initialized_deps = try allocator.create(std.StringHashMap(*Dependency));
initialized_deps.* = std.StringHashMap(*Dependency).init(allocator);
const self = try allocator.create(Build);
self.* = .{
.zig_exe = zig_exe,
.build_root = build_root,
.cache_root = cache_root,
.global_cache_root = global_cache_root,
.cache = cache,
.verbose = false,
.verbose_link = false,
.verbose_cc = false,
.verbose_air = false,
.verbose_llvm_ir = null,
.verbose_llvm_bc = null,
.verbose_cimport = false,
.verbose_llvm_cpu_features = false,
.invalid_user_input = false,
.allocator = allocator,
.user_input_options = UserInputOptionsMap.init(allocator),
.available_options_map = AvailableOptionsMap.init(allocator),
.available_options_list = ArrayList(AvailableOption).init(allocator),
.top_level_steps = .{},
.default_step = undefined,
.env_map = env_map,
.search_prefixes = ArrayList([]const u8).init(allocator),
.install_prefix = undefined,
.lib_dir = undefined,
.exe_dir = undefined,
.h_dir = undefined,
.dest_dir = env_map.get("DESTDIR"),
.installed_files = ArrayList(InstalledFile).init(allocator),
.install_tls = .{
.step = Step.init(.{
.id = .top_level,
.name = "install",
.owner = self,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.step = Step.init(.{
.id = .top_level,
.name = "uninstall",
.owner = self,
.makeFn = makeUninstall,
}),
.description = "Remove build artifacts from prefix path",
},
.zig_lib_dir = null,
.install_path = undefined,
.args = null,
.host = host,
.modules = std.StringArrayHashMap(*Module).init(allocator),
.initialized_deps = initialized_deps,
};
try self.top_level_steps.put(allocator, self.install_tls.step.name, &self.install_tls);
try self.top_level_steps.put(allocator, self.uninstall_tls.step.name, &self.uninstall_tls);
self.default_step = &self.install_tls.step;
return self;
}
fn createChild(
parent: *Build,
dep_name: []const u8,
build_root: Cache.Directory,
args: anytype,
) !*Build {
const child = try createChildOnly(parent, dep_name, build_root);
try applyArgs(child, args);
return child;
}
fn createChildOnly(parent: *Build, dep_name: []const u8, build_root: Cache.Directory) !*Build {
const allocator = parent.allocator;
const child = try allocator.create(Build);
child.* = .{
.allocator = allocator,
.install_tls = .{
.step = Step.init(.{
.id = .top_level,
.name = "install",
.owner = child,
}),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = .{
.step = Step.init(.{
.id = .top_level,
.name = "uninstall",
.owner = child,
.makeFn = makeUninstall,
}),
.description = "Remove build artifacts from prefix path",
},
.user_input_options = UserInputOptionsMap.init(allocator),
.available_options_map = AvailableOptionsMap.init(allocator),
.available_options_list = ArrayList(AvailableOption).init(allocator),
.verbose = parent.verbose,
.verbose_link = parent.verbose_link,
.verbose_cc = parent.verbose_cc,
.verbose_air = parent.verbose_air,
.verbose_llvm_ir = parent.verbose_llvm_ir,
.verbose_llvm_bc = parent.verbose_llvm_bc,
.verbose_cimport = parent.verbose_cimport,
.verbose_llvm_cpu_features = parent.verbose_llvm_cpu_features,
.reference_trace = parent.reference_trace,
.invalid_user_input = false,
.zig_exe = parent.zig_exe,
.default_step = undefined,
.env_map = parent.env_map,
.top_level_steps = .{},
.install_prefix = undefined,
.dest_dir = parent.dest_dir,
.lib_dir = parent.lib_dir,
.exe_dir = parent.exe_dir,
.h_dir = parent.h_dir,
.install_path = parent.install_path,
.sysroot = parent.sysroot,
.search_prefixes = ArrayList([]const u8).init(allocator),
.libc_file = parent.libc_file,
.installed_files = ArrayList(InstalledFile).init(allocator),
.build_root = build_root,
.cache_root = parent.cache_root,
.global_cache_root = parent.global_cache_root,
.cache = parent.cache,
.zig_lib_dir = parent.zig_lib_dir,
.debug_log_scopes = parent.debug_log_scopes,
.debug_compile_errors = parent.debug_compile_errors,
.debug_pkg_config = parent.debug_pkg_config,
.enable_darling = parent.enable_darling,
.enable_qemu = parent.enable_qemu,
.enable_rosetta = parent.enable_rosetta,
.enable_wasmtime = parent.enable_wasmtime,
.enable_wine = parent.enable_wine,
.glibc_runtimes_dir = parent.glibc_runtimes_dir,
.host = parent.host,
.dep_prefix = parent.fmt("{s}{s}.", .{ parent.dep_prefix, dep_name }),
.modules = std.StringArrayHashMap(*Module).init(allocator),
.initialized_deps = parent.initialized_deps,
};
try child.top_level_steps.put(allocator, child.install_tls.step.name, &child.install_tls);
try child.top_level_steps.put(allocator, child.uninstall_tls.step.name, &child.uninstall_tls);
child.default_step = &child.install_tls.step;
return child;
}
fn applyArgs(b: *Build, args: anytype) !void {
inline for (@typeInfo(@TypeOf(args)).Struct.fields) |field| {
const v = @field(args, field.name);
const T = @TypeOf(v);
switch (T) {
CrossTarget => {
try b.user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = try v.zigTriple(b.allocator) },
.used = false,
});
try b.user_input_options.put("cpu", .{
.name = "cpu",
.value = .{ .scalar = try serializeCpu(b.allocator, v.getCpu()) },
.used = false,
});
},
[]const u8 => {
try b.user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = v },
.used = false,
});
},
else => switch (@typeInfo(T)) {
.Bool => {
try b.user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = if (v) "true" else "false" },
.used = false,
});
},
.Enum, .EnumLiteral => {
try b.user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = @tagName(v) },
.used = false,
});
},
.Int => {
try b.user_input_options.put(field.name, .{
.name = field.name,
.value = .{ .scalar = try std.fmt.allocPrint(b.allocator, "{d}", .{v}) },
.used = false,
});
},
else => @compileError("option '" ++ field.name ++ "' has unsupported type: " ++ @typeName(T)),
},
}
}
// Create an installation directory local to this package. This will be used when
// dependant packages require a standard prefix, such as include directories for C headers.
var hash = b.cache.hash;
// Random bytes to make unique. Refresh this with new random bytes when
// implementation is modified in a non-backwards-compatible way.
hash.add(@as(u32, 0xd8cb0055));
hash.addBytes(b.dep_prefix);
// TODO additionally update the hash with `args`.
const digest = hash.final();
const install_prefix = try b.cache_root.join(b.allocator, &.{ "i", &digest });
b.resolveInstallPrefix(install_prefix, .{});
}
pub fn destroy(b: *Build) void {
b.env_map.deinit();
b.top_level_steps.deinit(b.allocator);
b.allocator.destroy(b);
}
/// This function is intended to be called by lib/build_runner.zig, not a build.zig file.
pub fn resolveInstallPrefix(self: *Build, install_prefix: ?[]const u8, dir_list: DirList) void {
if (self.dest_dir) |dest_dir| {
self.install_prefix = install_prefix orelse "/usr";
self.install_path = self.pathJoin(&.{ dest_dir, self.install_prefix });
} else {
self.install_prefix = install_prefix orelse
(self.build_root.join(self.allocator, &.{"zig-out"}) catch @panic("unhandled error"));
self.install_path = self.install_prefix;
}
var lib_list = [_][]const u8{ self.install_path, "lib" };
var exe_list = [_][]const u8{ self.install_path, "bin" };
var h_list = [_][]const u8{ self.install_path, "include" };
if (dir_list.lib_dir) |dir| {
if (std.fs.path.isAbsolute(dir)) lib_list[0] = self.dest_dir orelse "";
lib_list[1] = dir;
}
if (dir_list.exe_dir) |dir| {
if (std.fs.path.isAbsolute(dir)) exe_list[0] = self.dest_dir orelse "";
exe_list[1] = dir;
}
if (dir_list.include_dir) |dir| {
if (std.fs.path.isAbsolute(dir)) h_list[0] = self.dest_dir orelse "";
h_list[1] = dir;
}
self.lib_dir = self.pathJoin(&lib_list);
self.exe_dir = self.pathJoin(&exe_list);
self.h_dir = self.pathJoin(&h_list);
}
pub fn addOptions(self: *Build) *Step.Options {
return Step.Options.create(self);
}
pub const ExecutableOptions = struct {
name: []const u8,
root_source_file: ?FileSource = null,
version: ?std.SemanticVersion = null,
target: CrossTarget = .{},
optimize: std.builtin.Mode = .Debug,
linkage: ?Step.Compile.Linkage = null,
max_rss: usize = 0,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
};
pub fn addExecutable(b: *Build, options: ExecutableOptions) *Step.Compile {
return Step.Compile.create(b, .{
.name = options.name,
.root_source_file = options.root_source_file,
.version = options.version,
.target = options.target,
.optimize = options.optimize,
.kind = .exe,
.linkage = options.linkage,
.max_rss = options.max_rss,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
});
}
pub const ObjectOptions = struct {
name: []const u8,
root_source_file: ?FileSource = null,
target: CrossTarget,
optimize: std.builtin.Mode,
max_rss: usize = 0,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
};
pub fn addObject(b: *Build, options: ObjectOptions) *Step.Compile {
return Step.Compile.create(b, .{
.name = options.name,
.root_source_file = options.root_source_file,
.target = options.target,
.optimize = options.optimize,
.kind = .obj,
.max_rss = options.max_rss,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
});
}
pub const SharedLibraryOptions = struct {
name: []const u8,
root_source_file: ?FileSource = null,
version: ?std.SemanticVersion = null,
target: CrossTarget,
optimize: std.builtin.Mode,
max_rss: usize = 0,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
};
pub fn addSharedLibrary(b: *Build, options: SharedLibraryOptions) *Step.Compile {
return Step.Compile.create(b, .{
.name = options.name,
.root_source_file = options.root_source_file,
.kind = .lib,
.linkage = .dynamic,
.version = options.version,
.target = options.target,
.optimize = options.optimize,
.max_rss = options.max_rss,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
});
}
pub const StaticLibraryOptions = struct {
name: []const u8,
root_source_file: ?FileSource = null,
target: CrossTarget,
optimize: std.builtin.Mode,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
};
pub fn addStaticLibrary(b: *Build, options: StaticLibraryOptions) *Step.Compile {
return Step.Compile.create(b, .{
.name = options.name,
.root_source_file = options.root_source_file,
.kind = .lib,
.linkage = .static,
.version = options.version,
.target = options.target,
.optimize = options.optimize,
.max_rss = options.max_rss,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
});
}
pub const TestOptions = struct {
name: []const u8 = "test",
root_source_file: FileSource,
target: CrossTarget = .{},
optimize: std.builtin.Mode = .Debug,
version: ?std.SemanticVersion = null,
max_rss: usize = 0,
filter: ?[]const u8 = null,
test_runner: ?[]const u8 = null,
link_libc: ?bool = null,
single_threaded: ?bool = null,
use_llvm: ?bool = null,
use_lld: ?bool = null,
};
pub fn addTest(b: *Build, options: TestOptions) *Step.Compile {
return Step.Compile.create(b, .{
.name = options.name,
.kind = .@"test",
.root_source_file = options.root_source_file,
.target = options.target,
.optimize = options.optimize,
.max_rss = options.max_rss,
.filter = options.filter,
.test_runner = options.test_runner,
.link_libc = options.link_libc,
.single_threaded = options.single_threaded,
.use_llvm = options.use_llvm,
.use_lld = options.use_lld,
});
}
pub const AssemblyOptions = struct {
name: []const u8,
source_file: FileSource,
target: CrossTarget,
optimize: std.builtin.Mode,
max_rss: usize = 0,
};
pub fn addAssembly(b: *Build, options: AssemblyOptions) *Step.Compile {
const obj_step = Step.Compile.create(b, .{
.name = options.name,
.kind = .obj,
.root_source_file = null,
.target = options.target,
.optimize = options.optimize,
.max_rss = options.max_rss,
});
obj_step.addAssemblyFileSource(options.source_file.dupe(b));
return obj_step;
}
/// This function creates a module and adds it to the package's module set, making
/// it available to other packages which depend on this one.
/// `createModule` can be used instead to create a private module.
pub fn addModule(b: *Build, name: []const u8, options: CreateModuleOptions) *Module {
const module = b.createModule(options);
b.modules.put(b.dupe(name), module) catch @panic("OOM");
return module;
}
pub const ModuleDependency = struct {
name: []const u8,
module: *Module,
};
pub const CreateModuleOptions = struct {
source_file: FileSource,
dependencies: []const ModuleDependency = &.{},
};
/// This function creates a private module, to be used by the current package,
/// but not exposed to other packages depending on this one.
/// `addModule` can be used instead to create a public module.
pub fn createModule(b: *Build, options: CreateModuleOptions) *Module {
const module = b.allocator.create(Module) catch @panic("OOM");
module.* = .{
.builder = b,
.source_file = options.source_file,
.dependencies = moduleDependenciesToArrayHashMap(b.allocator, options.dependencies),
};
return module;
}
fn moduleDependenciesToArrayHashMap(arena: Allocator, deps: []const ModuleDependency) std.StringArrayHashMap(*Module) {
var result = std.StringArrayHashMap(*Module).init(arena);
for (deps) |dep| {
result.put(dep.name, dep.module) catch @panic("OOM");
}
return result;
}
/// Initializes a `Step.Run` with argv, which must at least have the path to the
/// executable. More command line arguments can be added with `addArg`,
/// `addArgs`, and `addArtifactArg`.
/// Be careful using this function, as it introduces a system dependency.
/// To run an executable built with zig build, see `Step.Compile.run`.
pub fn addSystemCommand(self: *Build, argv: []const []const u8) *Step.Run {
assert(argv.len >= 1);
const run_step = Step.Run.create(self, self.fmt("run {s}", .{argv[0]}));
run_step.addArgs(argv);
return run_step;
}
/// Creates a `Step.Run` with an executable built with `addExecutable`.
/// Add command line arguments with methods of `Step.Run`.
pub fn addRunArtifact(b: *Build, exe: *Step.Compile) *Step.Run {
// It doesn't have to be native. We catch that if you actually try to run it.
// Consider that this is declarative; the run step may not be run unless a user
// option is supplied.
const run_step = Step.Run.create(b, b.fmt("run {s}", .{exe.name}));
run_step.addArtifactArg(exe);
if (exe.kind == .@"test") {
run_step.enableTestRunnerMode();
}
if (exe.vcpkg_bin_path) |path| {
run_step.addPathDir(path);
}
return run_step;
}
/// Using the `values` provided, produces a C header file, possibly based on a
/// template input file (e.g. config.h.in).
/// When an input template file is provided, this function will fail the build
/// when an option not found in the input file is provided in `values`, and
/// when an option found in the input file is missing from `values`.
pub fn addConfigHeader(
b: *Build,
options: Step.ConfigHeader.Options,
values: anytype,
) *Step.ConfigHeader {
var options_copy = options;
if (options_copy.first_ret_addr == null)
options_copy.first_ret_addr = @returnAddress();
const config_header_step = Step.ConfigHeader.create(b, options_copy);
config_header_step.addValues(values);
return config_header_step;
}
/// Allocator.dupe without the need to handle out of memory.
pub fn dupe(self: *Build, bytes: []const u8) []u8 {
return self.allocator.dupe(u8, bytes) catch @panic("OOM");
}
/// Duplicates an array of strings without the need to handle out of memory.
pub fn dupeStrings(self: *Build, strings: []const []const u8) [][]u8 {
const array = self.allocator.alloc([]u8, strings.len) catch @panic("OOM");
for (strings, 0..) |s, i| {
array[i] = self.dupe(s);
}
return array;
}
/// Duplicates a path and converts all slashes to the OS's canonical path separator.
pub fn dupePath(self: *Build, bytes: []const u8) []u8 {
const the_copy = self.dupe(bytes);
for (the_copy) |*byte| {
switch (byte.*) {
'/', '\\' => byte.* = fs.path.sep,
else => {},
}
}
return the_copy;
}
pub fn addWriteFile(self: *Build, file_path: []const u8, data: []const u8) *Step.WriteFile {
const write_file_step = self.addWriteFiles();
_ = write_file_step.add(file_path, data);
return write_file_step;
}
pub fn addWriteFiles(b: *Build) *Step.WriteFile {
return Step.WriteFile.create(b);
}
pub fn addRemoveDirTree(self: *Build, dir_path: []const u8) *Step.RemoveDir {
const remove_dir_step = self.allocator.create(Step.RemoveDir) catch @panic("OOM");
remove_dir_step.* = Step.RemoveDir.init(self, dir_path);
return remove_dir_step;
}
pub fn addFmt(b: *Build, options: Step.Fmt.Options) *Step.Fmt {
return Step.Fmt.create(b, options);
}
pub fn addTranslateC(self: *Build, options: Step.TranslateC.Options) *Step.TranslateC {
return Step.TranslateC.create(self, options);
}
pub fn getInstallStep(self: *Build) *Step {
return &self.install_tls.step;
}
pub fn getUninstallStep(self: *Build) *Step {
return &self.uninstall_tls.step;
}
fn makeUninstall(uninstall_step: *Step, prog_node: *std.Progress.Node) anyerror!void {
_ = prog_node;
const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);
const self = @fieldParentPtr(Build, "uninstall_tls", uninstall_tls);
for (self.installed_files.items) |installed_file| {
const full_path = self.getInstallPath(installed_file.dir, installed_file.path);
if (self.verbose) {
log.info("rm {s}", .{full_path});
}
fs.cwd().deleteTree(full_path) catch {};
}
// TODO remove empty directories
}
pub fn option(self: *Build, comptime T: type, name_raw: []const u8, description_raw: []const u8) ?T {
const name = self.dupe(name_raw);
const description = self.dupe(description_raw);
const type_id = comptime typeToEnum(T);
const enum_options = if (type_id == .@"enum") blk: {
const fields = comptime std.meta.fields(T);
var options = ArrayList([]const u8).initCapacity(self.allocator, fields.len) catch @panic("OOM");
inline for (fields) |field| {
options.appendAssumeCapacity(field.name);
}
break :blk options.toOwnedSlice() catch @panic("OOM");
} else null;
const available_option = AvailableOption{
.name = name,
.type_id = type_id,
.description = description,
.enum_options = enum_options,
};
if ((self.available_options_map.fetchPut(name, available_option) catch @panic("OOM")) != null) {
panic("Option '{s}' declared twice", .{name});
}
self.available_options_list.append(available_option) catch @panic("OOM");
const option_ptr = self.user_input_options.getPtr(name) orelse return null;
option_ptr.used = true;
switch (type_id) {
.bool => switch (option_ptr.value) {
.flag => return true,
.scalar => |s| {
if (mem.eql(u8, s, "true")) {
return true;
} else if (mem.eql(u8, s, "false")) {
return false;
} else {
log.err("Expected -D{s} to be a boolean, but received '{s}'", .{ name, s });
self.markInvalidUserInput();
return null;
}
},
.list, .map => {
log.err("Expected -D{s} to be a boolean, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
},
.int => switch (option_ptr.value) {
.flag, .list, .map => {
log.err("Expected -D{s} to be an integer, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| {
const n = std.fmt.parseInt(T, s, 10) catch |err| switch (err) {
error.Overflow => {
log.err("-D{s} value {s} cannot fit into type {s}.", .{ name, s, @typeName(T) });
self.markInvalidUserInput();
return null;
},
else => {
log.err("Expected -D{s} to be an integer of type {s}.", .{ name, @typeName(T) });
self.markInvalidUserInput();
return null;
},
};
return n;
},
},
.float => switch (option_ptr.value) {
.flag, .map, .list => {
log.err("Expected -D{s} to be a float, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| {
const n = std.fmt.parseFloat(T, s) catch {
log.err("Expected -D{s} to be a float of type {s}.", .{ name, @typeName(T) });
self.markInvalidUserInput();
return null;
};
return n;
},
},
.@"enum" => switch (option_ptr.value) {
.flag, .map, .list => {
log.err("Expected -D{s} to be an enum, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| {
if (std.meta.stringToEnum(T, s)) |enum_lit| {
return enum_lit;
} else {
log.err("Expected -D{s} to be of type {s}.", .{ name, @typeName(T) });
self.markInvalidUserInput();
return null;
}
},
},
.string => switch (option_ptr.value) {
.flag, .list, .map => {
log.err("Expected -D{s} to be a string, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| return s,
},
.build_id => switch (option_ptr.value) {
.flag, .map, .list => {
log.err("Expected -D{s} to be an enum, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| {
if (Step.Compile.BuildId.parse(s)) |build_id| {
return build_id;
} else |err| {
log.err("unable to parse option '-D{s}': {s}", .{ name, @errorName(err) });
self.markInvalidUserInput();
return null;
}
},
},
.list => switch (option_ptr.value) {
.flag, .map => {
log.err("Expected -D{s} to be a list, but received a {s}.", .{
name, @tagName(option_ptr.value),
});
self.markInvalidUserInput();
return null;
},
.scalar => |s| {
return self.allocator.dupe([]const u8, &[_][]const u8{s}) catch @panic("OOM");
},
.list => |lst| return lst.items,
},
}
}
pub fn step(self: *Build, name: []const u8, description: []const u8) *Step {
const step_info = self.allocator.create(TopLevelStep) catch @panic("OOM");
step_info.* = .{
.step = Step.init(.{
.id = .top_level,
.name = name,
.owner = self,
}),
.description = self.dupe(description),
};
const gop = self.top_level_steps.getOrPut(self.allocator, name) catch @panic("OOM");
if (gop.found_existing) std.debug.panic("A top-level step with name \"{s}\" already exists", .{name});
gop.key_ptr.* = step_info.step.name;
gop.value_ptr.* = step_info;
return &step_info.step;
}
pub const StandardOptimizeOptionOptions = struct {
preferred_optimize_mode: ?std.builtin.Mode = null,
};
pub fn standardOptimizeOption(self: *Build, options: StandardOptimizeOptionOptions) std.builtin.Mode {
if (options.preferred_optimize_mode) |mode| {
if (self.option(bool, "release", "optimize for end users") orelse false) {
return mode;
} else {
return .Debug;
}
} else {
return self.option(
std.builtin.Mode,
"optimize",
"Prioritize performance, safety, or binary size (-O flag)",
) orelse .Debug;
}
}
pub const StandardTargetOptionsArgs = struct {
whitelist: ?[]const CrossTarget = null,