Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std.Build: add search prefix "exact" variant #22552

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions lib/compiler/build_runner.zig
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,13 @@ pub fn main() !void {
} else if (mem.eql(u8, arg, "--search-prefix")) {
const search_prefix = nextArgOrFatal(args, &arg_idx);
builder.addSearchPrefix(search_prefix);
} else if (mem.eql(u8, arg, "--search-prefix-exact")) {
const search_prefix_spec_path = nextArgOrFatal(args, &arg_idx);

const search_prefix = parseZonFile(std.Build.SearchPrefix.Exact, builder, search_prefix_spec_path) catch |err|
return fatal("Unable to parse ZON file '{s}': {s}", .{ search_prefix_spec_path, @errorName(err) });

builder.addSearchPrefixExact(search_prefix);
} else if (mem.eql(u8, arg, "--libc")) {
builder.libc_file = nextArgOrFatal(args, &arg_idx);
} else if (mem.eql(u8, arg, "--color")) {
Expand Down Expand Up @@ -1323,6 +1330,7 @@ fn usage(b: *std.Build, out_stream: anytype) !void {
\\ --search-prefix [path] Add a path to look for binaries, libraries, headers
\\ --sysroot [path] Set the system root directory (usually /)
\\ --libc [file] Provide a file which specifies libc paths
\\ --search-prefix-exact [file] Provide a file which specifies exact search paths
\\
\\ --system [pkgdir] Disable package fetching; enable all integrations
\\ -fsys=[name] Enable a system integration
Expand Down Expand Up @@ -1516,3 +1524,55 @@ fn createModuleDependenciesForStep(step: *Step) Allocator.Error!void {
};
}
}

/// Parse ZON file where all fields are paths relative to
/// current working directory.
fn parseZonFile(comptime T: type, b: *std.Build, path: []const u8) !T {
const spec_file = try std.fs.cwd().openFile(path, .{});
defer spec_file.close();

const gpa = b.allocator;

const spec = try std.zig.readSourceFileToEndAlloc(gpa, spec_file, null);
defer gpa.free(spec);

var ast: std.zig.Ast = try .parse(gpa, spec, .zon);
defer ast.deinit(gpa);

const zoir = try std.zig.ZonGen.generate(gpa, ast);
defer zoir.deinit(gpa);

if (zoir.hasCompileErrors()) {
std.log.err("Can't parse ZON file '{s}: {d} errors", .{ path, zoir.compile_errors.len });
for (zoir.compile_errors, 1..) |compile_error, i| {
std.log.err("[{d}] {s}", .{ i, compile_error.msg.get(zoir) });
for (compile_error.getNotes(zoir)) |note| {
std.log.err("note: {s}", .{note.msg.get(zoir)});
}
}
return process.exit(1);
}

var result: T = .{};
const root_struct = switch (std.zig.Zoir.Node.Index.root.get(zoir)) {
.struct_literal => |struct_literal| struct_literal,
.empty_literal => return result,
else => return fatal("Can't parse ZON file '{s}': not a struct", .{path}),
};

for (root_struct.names, 0..) |name_i, val_i| {
const name = name_i.get(zoir);
const val = root_struct.vals.at(@intCast(val_i)).get(zoir);

inline for (@typeInfo(T).@"struct".fields) |field| {
if (std.mem.eql(u8, name, field.name)) {
const string = switch (val) {
.string_literal => |string_literal| string_literal,
else => return fatal("Can't parse field '{s}' in ZON file '{s}': not a string", .{ field.name, path }),
};
@field(result, field.name) = .{ .cwd_relative = b.dupePath(string) };
}
}
}
return result;
}
49 changes: 46 additions & 3 deletions lib/std/Build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ exe_dir: []const u8,
h_dir: []const u8,
install_path: []const u8,
sysroot: ?[]const u8 = null,
search_prefixes: std.ArrayListUnmanaged([]const u8),
search_prefixes: std.ArrayListUnmanaged(SearchPrefix),
libc_file: ?[]const u8 = null,
/// Path to the directory containing build.zig.
build_root: Cache.Directory,
Expand Down Expand Up @@ -1993,11 +1993,13 @@ fn tryFindProgram(b: *Build, full_path: []const u8) ?[]const u8 {
pub fn findProgram(b: *Build, names: []const []const u8, paths: []const []const u8) error{FileNotFound}![]const u8 {
// TODO report error for ambiguous situations
for (b.search_prefixes.items) |search_prefix| {
const binaries_prefix = search_prefix.binaries(b) orelse continue;
for (names) |name| {
if (fs.path.isAbsolute(name)) {
return name;
}
return tryFindProgram(b, b.pathJoin(&.{ search_prefix, "bin", name })) orelse continue;
const binary_path = binaries_prefix.getPath3(b, null).joinString(b.allocator, name) catch @panic("OOM");
return tryFindProgram(b, binary_path) orelse continue;
}
}
if (b.graph.env_map.get("PATH")) |PATH| {
Expand Down Expand Up @@ -2085,8 +2087,49 @@ pub fn run(b: *Build, argv: []const []const u8) []u8 {
};
}

pub const SearchPrefix = union(enum) {
/// Try to find `bin`, `lib`, and `include` sub-dirs.
all: LazyPath,
/// Use as written, without guessing sub-dirs.
/// If some path is not passed, it will be skipped.
exact: SearchPrefix.Exact,

pub const Exact = struct {
binaries: ?LazyPath = null,
libraries: ?LazyPath = null,
includes: ?LazyPath = null,
};

pub fn binaries(self: SearchPrefix, b: *std.Build) ?LazyPath {
return switch (self) {
.all => |all| all.path(b, "bin"),
.exact => |exact| exact.binaries,
};
}

pub fn libraries(self: SearchPrefix, b: *std.Build) ?LazyPath {
return switch (self) {
.all => |all| all.path(b, "lib"),
.exact => |exact| exact.libraries,
};
}

pub fn includes(self: SearchPrefix, b: *std.Build) ?LazyPath {
return switch (self) {
.all => |all| all.path(b, "include"),
.exact => |exact| exact.includes,
};
}
};

pub fn addSearchPrefix(b: *Build, search_prefix: []const u8) void {
b.search_prefixes.append(b.allocator, b.dupePath(search_prefix)) catch @panic("OOM");
b.search_prefixes.append(b.allocator, .{
.all = .{ .cwd_relative = b.dupePath(search_prefix) },
}) catch @panic("OOM");
}

pub fn addSearchPrefixExact(b: *Build, search_prefix_exact: SearchPrefix.Exact) void {
b.search_prefixes.append(b.allocator, .{ .exact = search_prefix_exact }) catch @panic("OOM");
}

pub fn getInstallPath(b: *Build, dir: InstallDir, dest_rel_path: []const u8) []const u8 {
Expand Down
48 changes: 24 additions & 24 deletions lib/std/Build/Step/Compile.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1623,37 +1623,37 @@ fn getZigArgs(compile: *Compile, fuzz: bool) ![][]const u8 {

// -I and -L arguments that appear after the last --mod argument apply to all modules.
for (b.search_prefixes.items) |search_prefix| {
var prefix_dir = fs.cwd().openDir(search_prefix, .{}) catch |err| {
return step.fail("unable to open prefix directory '{s}': {s}", .{
search_prefix, @errorName(err),
});
};
defer prefix_dir.close();

// Avoid passing -L and -I flags for nonexistent directories.
// This prevents a warning, that should probably be upgraded to an error in Zig's
// CLI parsing code, when the linker sees an -L directory that does not exist.

if (prefix_dir.accessZ("lib", .{})) |_| {
try zig_args.appendSlice(&.{
"-L", b.pathJoin(&.{ search_prefix, "lib" }),
});
} else |err| switch (err) {
error.FileNotFound => {},
else => |e| return step.fail("unable to access '{s}/lib' directory: {s}", .{
search_prefix, @errorName(e),
}),
if (search_prefix.libraries(b)) |libraries_prefix| {
const libraries_path = libraries_prefix.getPath3(b, step);
if (libraries_path.access(".", .{})) {
try zig_args.appendSlice(&.{
"-L", libraries_path.toString(b.allocator) catch @panic("OOM"),
});
} else |err| switch (err) {
error.FileNotFound => {},
else => return step.fail("unable to access '{}' directory: {s}", .{
libraries_path, @errorName(err),
}),
}
}

if (prefix_dir.accessZ("include", .{})) |_| {
try zig_args.appendSlice(&.{
"-I", b.pathJoin(&.{ search_prefix, "include" }),
});
} else |err| switch (err) {
error.FileNotFound => {},
else => |e| return step.fail("unable to access '{s}/include' directory: {s}", .{
search_prefix, @errorName(e),
}),
if (search_prefix.includes(b)) |includes_prefix| {
const includes_path = includes_prefix.getPath3(b, step);
if (includes_path.access(".", .{})) {
try zig_args.appendSlice(&.{
"-I", includes_path.toString(b.allocator) catch @panic("OOM"),
});
} else |err| switch (err) {
error.FileNotFound => {},
else => return step.fail("unable to access '{}' directory: {s}", .{
includes_path, @errorName(err),
}),
}
}
}

Expand Down