/
build.zig
2481 lines (2171 loc) · 91.8 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 warn = std.debug.warn;
const ArrayList = std.ArrayList;
const StringHashMap = std.StringHashMap;
const Allocator = mem.Allocator;
const process = std.process;
const BufSet = std.BufSet;
const BufMap = std.BufMap;
const fmt_lib = std.fmt;
const File = std.fs.File;
pub const FmtStep = @import("build/fmt.zig").FmtStep;
pub const Builder = struct {
install_tls: TopLevelStep,
uninstall_tls: TopLevelStep,
allocator: *Allocator,
native_system_lib_paths: ArrayList([]const u8),
native_system_include_dirs: ArrayList([]const u8),
native_system_rpaths: ArrayList([]const u8),
user_input_options: UserInputOptionsMap,
available_options_map: AvailableOptionsMap,
available_options_list: ArrayList(AvailableOption),
verbose: bool,
verbose_tokenize: bool,
verbose_ast: bool,
verbose_link: bool,
verbose_cc: bool,
verbose_ir: bool,
verbose_llvm_ir: bool,
verbose_cimport: bool,
invalid_user_input: bool,
zig_exe: []const u8,
default_step: *Step,
env_map: *BufMap,
top_level_steps: ArrayList(*TopLevelStep),
install_prefix: ?[]const u8,
dest_dir: ?[]const u8,
lib_dir: []const u8,
exe_dir: []const u8,
install_path: []const u8,
search_prefixes: ArrayList([]const u8),
installed_files: ArrayList(InstalledFile),
build_root: []const u8,
cache_root: []const u8,
release_mode: ?builtin.Mode,
is_release: bool,
override_lib_dir: ?[]const u8,
vcpkg_root: VcpkgRoot,
pkg_config_pkg_list: ?(PkgConfigError![]const PkgConfigPkg) = null,
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,
};
const UserInputOption = struct {
name: []const u8,
value: UserValue,
used: bool,
};
const UserValue = union(enum) {
Flag: void,
Scalar: []const u8,
List: ArrayList([]const u8),
};
const TypeId = enum {
Bool,
Int,
Float,
String,
List,
};
const TopLevelStep = struct {
step: Step,
description: []const u8,
};
pub fn create(
allocator: *Allocator,
zig_exe: []const u8,
build_root: []const u8,
cache_root: []const u8,
) !*Builder {
const env_map = try allocator.create(BufMap);
env_map.* = try process.getEnvMap(allocator);
const self = try allocator.create(Builder);
self.* = Builder{
.zig_exe = zig_exe,
.build_root = build_root,
.cache_root = try fs.path.relative(allocator, build_root, cache_root),
.verbose = false,
.verbose_tokenize = false,
.verbose_ast = false,
.verbose_link = false,
.verbose_cc = false,
.verbose_ir = false,
.verbose_llvm_ir = false,
.verbose_cimport = false,
.invalid_user_input = false,
.allocator = allocator,
.native_system_lib_paths = ArrayList([]const u8).init(allocator),
.native_system_include_dirs = ArrayList([]const u8).init(allocator),
.native_system_rpaths = ArrayList([]const u8).init(allocator),
.user_input_options = UserInputOptionsMap.init(allocator),
.available_options_map = AvailableOptionsMap.init(allocator),
.available_options_list = ArrayList(AvailableOption).init(allocator),
.top_level_steps = ArrayList(*TopLevelStep).init(allocator),
.default_step = undefined,
.env_map = env_map,
.search_prefixes = ArrayList([]const u8).init(allocator),
.install_prefix = null,
.lib_dir = undefined,
.exe_dir = undefined,
.dest_dir = env_map.get("DESTDIR"),
.installed_files = ArrayList(InstalledFile).init(allocator),
.install_tls = TopLevelStep{
.step = Step.initNoOp("install", allocator),
.description = "Copy build artifacts to prefix path",
},
.uninstall_tls = TopLevelStep{
.step = Step.init("uninstall", allocator, makeUninstall),
.description = "Remove build artifacts from prefix path",
},
.release_mode = null,
.is_release = false,
.override_lib_dir = null,
.install_path = undefined,
.vcpkg_root = VcpkgRoot{ .Unattempted = {} },
};
try self.top_level_steps.append(&self.install_tls);
try self.top_level_steps.append(&self.uninstall_tls);
self.detectNativeSystemPaths();
self.default_step = &self.install_tls.step;
return self;
}
pub fn destroy(self: *Builder) void {
self.native_system_lib_paths.deinit();
self.native_system_include_dirs.deinit();
self.native_system_rpaths.deinit();
self.env_map.deinit();
self.top_level_steps.deinit();
self.allocator.destroy(self);
}
/// This function is intended to be called by std/special/build_runner.zig, not a build.zig file.
pub fn setInstallPrefix(self: *Builder, optional_prefix: ?[]const u8) void {
self.install_prefix = optional_prefix;
}
/// This function is intended to be called by std/special/build_runner.zig, not a build.zig file.
pub fn resolveInstallPrefix(self: *Builder) void {
if (self.dest_dir) |dest_dir| {
const install_prefix = self.install_prefix orelse "/usr";
self.install_path = fs.path.join(self.allocator, &[_][]const u8{ dest_dir, install_prefix }) catch unreachable;
} else {
const install_prefix = self.install_prefix orelse blk: {
const p = self.cache_root;
self.install_prefix = p;
break :blk p;
};
self.install_path = install_prefix;
}
self.lib_dir = fs.path.join(self.allocator, &[_][]const u8{ self.install_path, "lib" }) catch unreachable;
self.exe_dir = fs.path.join(self.allocator, &[_][]const u8{ self.install_path, "bin" }) catch unreachable;
}
pub fn addExecutable(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
return LibExeObjStep.createExecutable(self, name, root_src, false);
}
pub fn addObject(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
return LibExeObjStep.createObject(self, name, root_src);
}
pub fn addSharedLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8, ver: Version) *LibExeObjStep {
return LibExeObjStep.createSharedLibrary(self, name, root_src, ver);
}
pub fn addStaticLibrary(self: *Builder, name: []const u8, root_src: ?[]const u8) *LibExeObjStep {
return LibExeObjStep.createStaticLibrary(self, name, root_src);
}
pub fn addTest(self: *Builder, root_src: []const u8) *LibExeObjStep {
return LibExeObjStep.createTest(self, "test", root_src);
}
pub fn addAssemble(self: *Builder, name: []const u8, src: []const u8) *LibExeObjStep {
const obj_step = LibExeObjStep.createObject(self, name, null);
obj_step.addAssemblyFile(src);
return obj_step;
}
/// Initializes a RunStep 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 `LibExeObjStep.run`.
pub fn addSystemCommand(self: *Builder, argv: []const []const u8) *RunStep {
assert(argv.len >= 1);
const run_step = RunStep.create(self, self.fmt("run {}", .{argv[0]}));
run_step.addArgs(argv);
return run_step;
}
fn dupe(self: *Builder, bytes: []const u8) []u8 {
return mem.dupe(self.allocator, u8, bytes) catch unreachable;
}
fn dupePath(self: *Builder, 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: *Builder, file_path: []const u8, data: []const u8) *WriteFileStep {
const write_file_step = self.allocator.create(WriteFileStep) catch unreachable;
write_file_step.* = WriteFileStep.init(self, file_path, data);
return write_file_step;
}
pub fn addLog(self: *Builder, comptime format: []const u8, args: var) *LogStep {
const data = self.fmt(format, args);
const log_step = self.allocator.create(LogStep) catch unreachable;
log_step.* = LogStep.init(self, data);
return log_step;
}
pub fn addRemoveDirTree(self: *Builder, dir_path: []const u8) *RemoveDirStep {
const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable;
remove_dir_step.* = RemoveDirStep.init(self, dir_path);
return remove_dir_step;
}
pub fn addFmt(self: *Builder, paths: []const []const u8) *FmtStep {
return FmtStep.create(self, paths);
}
pub fn version(self: *const Builder, major: u32, minor: u32, patch: u32) Version {
return Version{
.major = major,
.minor = minor,
.patch = patch,
};
}
pub fn addNativeSystemIncludeDir(self: *Builder, path: []const u8) void {
self.native_system_include_dirs.append(path) catch unreachable;
}
pub fn addNativeSystemRPath(self: *Builder, path: []const u8) void {
self.native_system_rpaths.append(path) catch unreachable;
}
pub fn addNativeSystemLibPath(self: *Builder, path: []const u8) void {
self.native_system_lib_paths.append(path) catch unreachable;
}
pub fn make(self: *Builder, step_names: []const []const u8) !void {
try self.makePath(self.cache_root);
var wanted_steps = ArrayList(*Step).init(self.allocator);
defer wanted_steps.deinit();
if (step_names.len == 0) {
try wanted_steps.append(self.default_step);
} else {
for (step_names) |step_name| {
const s = try self.getTopLevelStepByName(step_name);
try wanted_steps.append(s);
}
}
for (wanted_steps.toSliceConst()) |s| {
try self.makeOneStep(s);
}
}
pub fn getInstallStep(self: *Builder) *Step {
return &self.install_tls.step;
}
pub fn getUninstallStep(self: *Builder) *Step {
return &self.uninstall_tls.step;
}
fn makeUninstall(uninstall_step: *Step) anyerror!void {
const uninstall_tls = @fieldParentPtr(TopLevelStep, "step", uninstall_step);
const self = @fieldParentPtr(Builder, "uninstall_tls", uninstall_tls);
for (self.installed_files.toSliceConst()) |installed_file| {
const full_path = self.getInstallPath(installed_file.dir, installed_file.path);
if (self.verbose) {
warn("rm {}\n", .{full_path});
}
fs.deleteTree(full_path) catch {};
}
// TODO remove empty directories
}
fn makeOneStep(self: *Builder, s: *Step) anyerror!void {
if (s.loop_flag) {
warn("Dependency loop detected:\n {}\n", .{s.name});
return error.DependencyLoopDetected;
}
s.loop_flag = true;
for (s.dependencies.toSlice()) |dep| {
self.makeOneStep(dep) catch |err| {
if (err == error.DependencyLoopDetected) {
warn(" {}\n", .{s.name});
}
return err;
};
}
s.loop_flag = false;
try s.make();
}
fn getTopLevelStepByName(self: *Builder, name: []const u8) !*Step {
for (self.top_level_steps.toSliceConst()) |top_level_step| {
if (mem.eql(u8, top_level_step.step.name, name)) {
return &top_level_step.step;
}
}
warn("Cannot run step '{}' because it does not exist\n", .{name});
return error.InvalidStepName;
}
fn detectNativeSystemPaths(self: *Builder) void {
var is_nixos = false;
if (process.getEnvVarOwned(self.allocator, "NIX_CFLAGS_COMPILE")) |nix_cflags_compile| {
is_nixos = true;
var it = mem.tokenize(nix_cflags_compile, " ");
while (true) {
const word = it.next() orelse break;
if (mem.eql(u8, word, "-isystem")) {
const include_path = it.next() orelse {
warn("Expected argument after -isystem in NIX_CFLAGS_COMPILE\n", .{});
break;
};
self.addNativeSystemIncludeDir(include_path);
} else {
warn("Unrecognized C flag from NIX_CFLAGS_COMPILE: {}\n", .{word});
break;
}
}
} else |err| {
assert(err == error.EnvironmentVariableNotFound);
}
if (process.getEnvVarOwned(self.allocator, "NIX_LDFLAGS")) |nix_ldflags| {
is_nixos = true;
var it = mem.tokenize(nix_ldflags, " ");
while (true) {
const word = it.next() orelse break;
if (mem.eql(u8, word, "-rpath")) {
const rpath = it.next() orelse {
warn("Expected argument after -rpath in NIX_LDFLAGS\n", .{});
break;
};
self.addNativeSystemRPath(rpath);
} else if (word.len > 2 and word[0] == '-' and word[1] == 'L') {
const lib_path = word[2..];
self.addNativeSystemLibPath(lib_path);
} else {
warn("Unrecognized C flag from NIX_LDFLAGS: {}\n", .{word});
break;
}
}
} else |err| {
assert(err == error.EnvironmentVariableNotFound);
}
if (is_nixos) return;
switch (builtin.os) {
.windows => {},
else => {
const triple = (Target{
.Cross = CrossTarget{
.arch = builtin.arch,
.os = builtin.os,
.abi = builtin.abi,
},
}).linuxTriple(self.allocator);
// TODO: $ ld --verbose | grep SEARCH_DIR
// the output contains some paths that end with lib64, maybe include them too?
// also, what is the best possible order of things?
self.addNativeSystemIncludeDir("/usr/local/include");
self.addNativeSystemLibPath("/usr/local/lib");
self.addNativeSystemIncludeDir(self.fmt("/usr/include/{}", .{triple}));
self.addNativeSystemLibPath(self.fmt("/usr/lib/{}", .{triple}));
self.addNativeSystemIncludeDir("/usr/include");
self.addNativeSystemLibPath("/usr/lib");
// example: on a 64-bit debian-based linux distro, with zlib installed from apt:
// zlib.h is in /usr/include (added above)
// libz.so.1 is in /lib/x86_64-linux-gnu (added here)
self.addNativeSystemLibPath(self.fmt("/lib/{}", .{triple}));
},
}
}
pub fn option(self: *Builder, comptime T: type, name: []const u8, description: []const u8) ?T {
const type_id = comptime typeToEnum(T);
const available_option = AvailableOption{
.name = name,
.type_id = type_id,
.description = description,
};
if ((self.available_options_map.put(name, available_option) catch unreachable) != null) {
panic("Option '{}' declared twice", .{name});
}
self.available_options_list.append(available_option) catch unreachable;
const entry = self.user_input_options.get(name) orelse return null;
entry.value.used = true;
switch (type_id) {
TypeId.Bool => switch (entry.value.value) {
UserValue.Flag => return true,
UserValue.Scalar => |s| {
if (mem.eql(u8, s, "true")) {
return true;
} else if (mem.eql(u8, s, "false")) {
return false;
} else {
warn("Expected -D{} to be a boolean, but received '{}'\n", .{ name, s });
self.markInvalidUserInput();
return null;
}
},
UserValue.List => {
warn("Expected -D{} to be a boolean, but received a list.\n", .{name});
self.markInvalidUserInput();
return null;
},
},
TypeId.Int => panic("TODO integer options to build script", .{}),
TypeId.Float => panic("TODO float options to build script", .{}),
TypeId.String => switch (entry.value.value) {
UserValue.Flag => {
warn("Expected -D{} to be a string, but received a boolean.\n", .{name});
self.markInvalidUserInput();
return null;
},
UserValue.List => {
warn("Expected -D{} to be a string, but received a list.\n", .{name});
self.markInvalidUserInput();
return null;
},
UserValue.Scalar => |s| return s,
},
TypeId.List => panic("TODO list options to build script", .{}),
}
}
pub fn step(self: *Builder, name: []const u8, description: []const u8) *Step {
const step_info = self.allocator.create(TopLevelStep) catch unreachable;
step_info.* = TopLevelStep{
.step = Step.initNoOp(name, self.allocator),
.description = description,
};
self.top_level_steps.append(step_info) catch unreachable;
return &step_info.step;
}
/// This provides the -Drelease option to the build user and does not give them the choice.
pub fn setPreferredReleaseMode(self: *Builder, mode: builtin.Mode) void {
if (self.release_mode != null) {
@panic("setPreferredReleaseMode must be called before standardReleaseOptions and may not be called twice");
}
const description = self.fmt("create a release build ({})", .{@tagName(mode)});
self.is_release = self.option(bool, "release", description) orelse false;
self.release_mode = if (self.is_release) mode else builtin.Mode.Debug;
}
/// If you call this without first calling `setPreferredReleaseMode` then it gives the build user
/// the choice of what kind of release.
pub fn standardReleaseOptions(self: *Builder) builtin.Mode {
if (self.release_mode) |mode| return mode;
const release_safe = self.option(bool, "release-safe", "optimizations on and safety on") orelse false;
const release_fast = self.option(bool, "release-fast", "optimizations on and safety off") orelse false;
const release_small = self.option(bool, "release-small", "size optimizations on and safety off") orelse false;
const mode = if (release_safe and !release_fast and !release_small)
builtin.Mode.ReleaseSafe
else if (release_fast and !release_safe and !release_small)
builtin.Mode.ReleaseFast
else if (release_small and !release_fast and !release_safe)
builtin.Mode.ReleaseSmall
else if (!release_fast and !release_safe and !release_small)
builtin.Mode.Debug
else x: {
warn("Multiple release modes (of -Drelease-safe, -Drelease-fast and -Drelease-small)", .{});
self.markInvalidUserInput();
break :x builtin.Mode.Debug;
};
self.is_release = mode != .Debug;
self.release_mode = mode;
return mode;
}
/// Exposes standard `zig build` options for choosing a target. Pass `null` to support all targets.
pub fn standardTargetOptions(self: *Builder, supported_targets: ?[]const Target) Target {
if (supported_targets) |target_list| {
// TODO detect multiple args and emit an error message
// there's probably a better way to collect the target
for (target_list) |targ| {
const targ_str = targ.zigTriple(self.allocator) catch unreachable;
const targ_desc = targ.allocDescription(self.allocator) catch unreachable;
const this_targ_opt = self.option(bool, targ_str, targ_desc) orelse false;
if (this_targ_opt) {
return targ;
}
}
return Target.Native;
} else {
const target_str = self.option([]const u8, "target", "the target to build for") orelse return Target.Native;
return Target.parse(target_str) catch unreachable; // TODO better error message for bad target
}
}
pub fn addUserInputOption(self: *Builder, name: []const u8, value: []const u8) !bool {
const gop = try self.user_input_options.getOrPut(name);
if (!gop.found_existing) {
gop.kv.value = UserInputOption{
.name = name,
.value = UserValue{ .Scalar = value },
.used = false,
};
return false;
}
// option already exists
switch (gop.kv.value.value) {
UserValue.Scalar => |s| {
// turn it into a list
var list = ArrayList([]const u8).init(self.allocator);
list.append(s) catch unreachable;
list.append(value) catch unreachable;
_ = self.user_input_options.put(name, UserInputOption{
.name = name,
.value = UserValue{ .List = list },
.used = false,
}) catch unreachable;
},
UserValue.List => |*list| {
// append to the list
list.append(value) catch unreachable;
_ = self.user_input_options.put(name, UserInputOption{
.name = name,
.value = UserValue{ .List = list.* },
.used = false,
}) catch unreachable;
},
UserValue.Flag => {
warn("Option '-D{}={}' conflicts with flag '-D{}'.\n", .{ name, value, name });
return true;
},
}
return false;
}
pub fn addUserInputFlag(self: *Builder, name: []const u8) !bool {
const gop = try self.user_input_options.getOrPut(name);
if (!gop.found_existing) {
gop.kv.value = UserInputOption{
.name = name,
.value = UserValue{ .Flag = {} },
.used = false,
};
return false;
}
// option already exists
switch (gop.kv.value.value) {
UserValue.Scalar => |s| {
warn("Flag '-D{}' conflicts with option '-D{}={}'.\n", .{ name, name, s });
return true;
},
UserValue.List => {
warn("Flag '-D{}' conflicts with multiple options of the same name.\n", .{name});
return true;
},
UserValue.Flag => {},
}
return false;
}
fn typeToEnum(comptime T: type) TypeId {
return switch (@typeId(T)) {
builtin.TypeId.Int => TypeId.Int,
builtin.TypeId.Float => TypeId.Float,
builtin.TypeId.Bool => TypeId.Bool,
else => switch (T) {
[]const u8 => TypeId.String,
[]const []const u8 => TypeId.List,
else => @compileError("Unsupported type: " ++ @typeName(T)),
},
};
}
fn markInvalidUserInput(self: *Builder) void {
self.invalid_user_input = true;
}
pub fn typeIdName(id: TypeId) []const u8 {
return switch (id) {
TypeId.Bool => "bool",
TypeId.Int => "int",
TypeId.Float => "float",
TypeId.String => "string",
TypeId.List => "list",
};
}
pub fn validateUserInputDidItFail(self: *Builder) bool {
// make sure all args are used
var it = self.user_input_options.iterator();
while (true) {
const entry = it.next() orelse break;
if (!entry.value.used) {
warn("Invalid option: -D{}\n\n", .{entry.key});
self.markInvalidUserInput();
}
}
return self.invalid_user_input;
}
fn spawnChild(self: *Builder, argv: []const []const u8) !void {
return self.spawnChildEnvMap(null, self.env_map, argv);
}
fn printCmd(cwd: ?[]const u8, argv: []const []const u8) void {
if (cwd) |yes_cwd| warn("cd {} && ", .{yes_cwd});
for (argv) |arg| {
warn("{} ", .{arg});
}
warn("\n", .{});
}
fn spawnChildEnvMap(self: *Builder, cwd: ?[]const u8, env_map: *const BufMap, argv: []const []const u8) !void {
if (self.verbose) {
printCmd(cwd, argv);
}
const child = std.ChildProcess.init(argv, self.allocator) catch unreachable;
defer child.deinit();
child.cwd = cwd;
child.env_map = env_map;
const term = child.spawnAndWait() catch |err| {
warn("Unable to spawn {}: {}\n", .{ argv[0], @errorName(err) });
return err;
};
switch (term) {
.Exited => |code| {
if (code != 0) {
warn("The following command exited with error code {}:\n", .{code});
printCmd(cwd, argv);
return error.UncleanExit;
}
},
else => {
warn("The following command terminated unexpectedly:\n", .{});
printCmd(cwd, argv);
return error.UncleanExit;
},
}
}
pub fn makePath(self: *Builder, path: []const u8) !void {
fs.makePath(self.allocator, self.pathFromRoot(path)) catch |err| {
warn("Unable to create path {}: {}\n", .{ path, @errorName(err) });
return err;
};
}
pub fn installArtifact(self: *Builder, artifact: *LibExeObjStep) void {
self.getInstallStep().dependOn(&self.addInstallArtifact(artifact).step);
}
pub fn addInstallArtifact(self: *Builder, artifact: *LibExeObjStep) *InstallArtifactStep {
return InstallArtifactStep.create(self, artifact);
}
///`dest_rel_path` is relative to prefix path
pub fn installFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void {
self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Prefix, dest_rel_path).step);
}
pub fn installDirectory(self: *Builder, options: InstallDirectoryOptions) void {
self.getInstallStep().dependOn(&self.addInstallDirectory(options).step);
}
///`dest_rel_path` is relative to bin path
pub fn installBinFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void {
self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Bin, dest_rel_path).step);
}
///`dest_rel_path` is relative to lib path
pub fn installLibFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) void {
self.getInstallStep().dependOn(&self.addInstallFileWithDir(src_path, .Lib, dest_rel_path).step);
}
///`dest_rel_path` is relative to install prefix path
pub fn addInstallFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep {
return self.addInstallFileWithDir(src_path, .Prefix, dest_rel_path);
}
///`dest_rel_path` is relative to bin path
pub fn addInstallBinFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep {
return self.addInstallFileWithDir(src_path, .Bin, dest_rel_path);
}
///`dest_rel_path` is relative to lib path
pub fn addInstallLibFile(self: *Builder, src_path: []const u8, dest_rel_path: []const u8) *InstallFileStep {
return self.addInstallFileWithDir(src_path, .Lib, dest_rel_path);
}
pub fn addInstallFileWithDir(
self: *Builder,
src_path: []const u8,
install_dir: InstallDir,
dest_rel_path: []const u8,
) *InstallFileStep {
const install_step = self.allocator.create(InstallFileStep) catch unreachable;
install_step.* = InstallFileStep.init(self, src_path, install_dir, dest_rel_path);
return install_step;
}
pub fn addInstallDirectory(self: *Builder, options: InstallDirectoryOptions) *InstallDirStep {
const install_step = self.allocator.create(InstallDirStep) catch unreachable;
install_step.* = InstallDirStep.init(self, options);
return install_step;
}
pub fn pushInstalledFile(self: *Builder, dir: InstallDir, dest_rel_path: []const u8) void {
self.installed_files.append(InstalledFile{
.dir = dir,
.path = dest_rel_path,
}) catch unreachable;
}
fn updateFile(self: *Builder, source_path: []const u8, dest_path: []const u8) !void {
if (self.verbose) {
warn("cp {} {} ", .{ source_path, dest_path });
}
const prev_status = try fs.updateFile(source_path, dest_path);
if (self.verbose) switch (prev_status) {
.stale => warn("# installed\n", .{}),
.fresh => warn("# up-to-date\n", .{}),
};
}
fn pathFromRoot(self: *Builder, rel_path: []const u8) []u8 {
return fs.path.resolve(self.allocator, &[_][]const u8{ self.build_root, rel_path }) catch unreachable;
}
pub fn fmt(self: *Builder, comptime format: []const u8, args: var) []u8 {
return fmt_lib.allocPrint(self.allocator, format, args) catch unreachable;
}
pub fn findProgram(self: *Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 {
// TODO report error for ambiguous situations
const exe_extension = (Target{ .Native = {} }).exeFileExt();
for (self.search_prefixes.toSliceConst()) |search_prefix| {
for (names) |name| {
if (fs.path.isAbsolute(name)) {
return name;
}
const full_path = try fs.path.join(self.allocator, &[_][]const u8{
search_prefix,
"bin",
self.fmt("{}{}", .{ name, exe_extension }),
});
return fs.realpathAlloc(self.allocator, full_path) catch continue;
}
}
if (self.env_map.get("PATH")) |PATH| {
for (names) |name| {
if (fs.path.isAbsolute(name)) {
return name;
}
var it = mem.tokenize(PATH, &[_]u8{fs.path.delimiter});
while (it.next()) |path| {
const full_path = try fs.path.join(self.allocator, &[_][]const u8{
path,
self.fmt("{}{}", .{ name, exe_extension }),
});
return fs.realpathAlloc(self.allocator, full_path) catch continue;
}
}
}
for (names) |name| {
if (fs.path.isAbsolute(name)) {
return name;
}
for (paths) |path| {
const full_path = try fs.path.join(self.allocator, &[_][]const u8{
path,
self.fmt("{}{}", .{ name, exe_extension }),
});
return fs.realpathAlloc(self.allocator, full_path) catch continue;
}
}
return error.FileNotFound;
}
pub fn execAllowFail(
self: *Builder,
argv: []const []const u8,
out_code: *u8,
stderr_behavior: std.ChildProcess.StdIo,
) ![]u8 {
assert(argv.len != 0);
const max_output_size = 400 * 1024;
const child = try std.ChildProcess.init(argv, self.allocator);
defer child.deinit();
child.stdin_behavior = .Ignore;
child.stdout_behavior = .Pipe;
child.stderr_behavior = stderr_behavior;
try child.spawn();
var stdout = std.Buffer.initNull(self.allocator);
defer std.Buffer.deinit(&stdout);
var stdout_file_in_stream = child.stdout.?.inStream();
try stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size);
const term = try child.wait();
switch (term) {
.Exited => |code| {
if (code != 0) {
out_code.* = @truncate(u8, code);
return error.ExitCodeFailure;
}
return stdout.toOwnedSlice();
},
.Signal, .Stopped, .Unknown => |code| {
out_code.* = @truncate(u8, code);
return error.ProcessTerminated;
},
}
}
pub fn exec(self: *Builder, argv: []const []const u8) ![]u8 {
assert(argv.len != 0);
if (self.verbose) {
printCmd(null, argv);
}
var code: u8 = undefined;
return self.execAllowFail(argv, &code, .Inherit) catch |err| switch (err) {
error.FileNotFound => {
warn("Unable to spawn the following command: file not found\n", .{});
printCmd(null, argv);
std.os.exit(@truncate(u8, code));
},
error.ExitCodeFailure => {
warn("The following command exited with error code {}:\n", .{code});
printCmd(null, argv);
std.os.exit(@truncate(u8, code));
},
error.ProcessTerminated => {
warn("The following command terminated unexpectedly:\n", .{});
printCmd(null, argv);
std.os.exit(@truncate(u8, code));
},
else => |e| return e,
};
}
pub fn addSearchPrefix(self: *Builder, search_prefix: []const u8) void {
self.search_prefixes.append(search_prefix) catch unreachable;
}
fn getInstallPath(self: *Builder, dir: InstallDir, dest_rel_path: []const u8) []const u8 {
const base_dir = switch (dir) {
.Prefix => self.install_path,
.Bin => self.exe_dir,
.Lib => self.lib_dir,
};
return fs.path.resolve(
self.allocator,
&[_][]const u8{ base_dir, dest_rel_path },
) catch unreachable;
}
fn execPkgConfigList(self: *Builder, out_code: *u8) ![]const PkgConfigPkg {
const stdout = try self.execAllowFail(&[_][]const u8{ "pkg-config", "--list-all" }, out_code, .Ignore);
var list = ArrayList(PkgConfigPkg).init(self.allocator);
var line_it = mem.tokenize(stdout, "\r\n");
while (line_it.next()) |line| {
if (mem.trim(u8, line, " \t").len == 0) continue;
var tok_it = mem.tokenize(line, " \t");
try list.append(PkgConfigPkg{
.name = tok_it.next() orelse return error.PkgConfigInvalidOutput,
.desc = tok_it.rest(),
});
}
return list.toSliceConst();
}
fn getPkgConfigList(self: *Builder) ![]const PkgConfigPkg {
if (self.pkg_config_pkg_list) |res| {
return res;
}
var code: u8 = undefined;
if (self.execPkgConfigList(&code)) |list| {
self.pkg_config_pkg_list = list;
return list;
} else |err| {
const result = switch (err) {
error.ProcessTerminated => error.PkgConfigCrashed,
error.ExitCodeFailure => error.PkgConfigFailed,
error.FileNotFound => error.PkgConfigNotInstalled,
error.InvalidName => error.PkgConfigNotInstalled,
error.PkgConfigInvalidOutput => error.PkgConfigInvalidOutput,
else => return err,
};
self.pkg_config_pkg_list = result;
return result;
}
}
};
test "builder.findProgram compiles" {
const builder = try Builder.create(std.heap.page_allocator, "zig", "zig-cache", "zig-cache");
_ = builder.findProgram(&[_][]const u8{}, &[_][]const u8{}) catch null;
}
/// Deprecated. Use `builtin.Version`.
pub const Version = builtin.Version;
/// Deprecated. Use `std.Target.Cross`.
pub const CrossTarget = std.Target.Cross;
/// Deprecated. Use `std.Target`.
pub const Target = std.Target;
const Pkg = struct {
name: []const u8,
path: []const u8,
};
const CSourceFile = struct {