├── .gitignore ├── LICENSE ├── README.md ├── assert ├── assert.go └── assert_fast.go ├── build.zig ├── build.zig.zon └── go.mod /.gitignore: -------------------------------------------------------------------------------- 1 | .zig-cache/ 2 | zig-out/ 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2024 Tim Culverhouse 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zig4go 2 | 3 | We all know that zig is a great build system. zig4go makes it easy to build go 4 | projects using zig. 5 | 6 | [![Static Badge](https://img.shields.io/badge/v0.13(stable)-orange?logo=Zig&logoColor=Orange&label=Zig&labelColor=Orange)](https://ziglang.org/download/) 7 | 8 | ## Usage 9 | 10 | zig4go will do a few magic things for you: 11 | 12 | 1. When using CGO, it will automatically set up a static build using zig cc 13 | 2. The release mode is passed as a build tag to go (ie `-tags ReleaseSafe`) 14 | 15 | ```zig 16 | const std = @import("std"); 17 | const go = @import("go"); 18 | 19 | pub fn build(b: *std.Build) void { 20 | const target = b.standardTargetOptions(.{}); 21 | const optimize = b.standardOptimizeOption(.{}); 22 | 23 | // Set up the build runner 24 | const go_build = go.addExecutable(b, .{ 25 | .name = "app", 26 | .target = target, 27 | .optimize = optimize, 28 | .package_path = b.path("cmd/app"), 29 | }); 30 | 31 | // Add a run step to our build 32 | const run_cmd = go_build.addRunStep(); 33 | if (b.args) |args| { 34 | run_cmd.addArgs(args); 35 | } 36 | const run_step = b.step("run", "Run the app"); 37 | run_step.dependOn(&run_cmd.step); 38 | 39 | // Install the executable 40 | go_build.addInstallStep(); 41 | } 42 | ``` 43 | 44 | ## Assert 45 | 46 | zig4go also includes a very simple assert package. This package contains two 47 | files: `assert_fast.go` which is used for ReleaseFast builds and `assert.go` 48 | which is used for all other builds. zig4go sets the build mode as a build tag, 49 | which the go compiler uses to conditionally compile one of these files. The 50 | `_fast` version is a no-op function, while the standard version contains 51 | assertion logic. The go compiler [optimizes](https://godbolt.org/z/cfMs46ahb) 52 | the no-op function away, so (just like in zig), you can pepper your codebase 53 | with assertions and compile them away with no performance cost in a ReleaseFast 54 | build. 55 | 56 | ## Contributing 57 | 58 | Contributions are welcome. Some ideas: 59 | 60 | - Add a nice way to cross compile 61 | - Add more of the go build options 62 | - Make a ReleaseSmall build actually small 63 | - Add an option to download go from official sources 64 | -------------------------------------------------------------------------------- /assert/assert.go: -------------------------------------------------------------------------------- 1 | //go:build !ReleaseFast 2 | 3 | package assert 4 | 5 | func True(condition bool) { 6 | if !condition { 7 | panic("assertion failure: value is not true") 8 | } 9 | } 10 | 11 | func False(condition bool) { 12 | if !condition { 13 | panic("assertion failure: value is not false") 14 | } 15 | } 16 | 17 | func NotNil(v any) { 18 | if v == nil { 19 | panic("assertion failure: value is nil") 20 | } 21 | } 22 | 23 | func Nil(v any) { 24 | if v != nil { 25 | panic("assertion failure: value is not nil") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /assert/assert_fast.go: -------------------------------------------------------------------------------- 1 | //go:build ReleaseFast || ReleaseSmall 2 | 3 | package assert 4 | 5 | func True(condition bool) {} 6 | 7 | func False(condition bool) {} 8 | 9 | func NotNil(v any) {} 10 | 11 | func Nil(v any) {} 12 | -------------------------------------------------------------------------------- /build.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | 3 | pub fn addExecutable(b: *std.Build, options: BuildStep.Options) *BuildStep { 4 | return BuildStep.create(b, options); 5 | } 6 | 7 | pub fn build(b: *std.Build) void { 8 | _ = b; 9 | } 10 | 11 | /// Runs `go build` with relevant flags 12 | pub const BuildStep = struct { 13 | step: std.Build.Step, 14 | generated_bin: ?*std.Build.GeneratedFile, 15 | opts: Options, 16 | 17 | pub const Options = struct { 18 | name: []const u8, 19 | target: std.Build.ResolvedTarget, 20 | optimize: std.builtin.OptimizeMode, 21 | package_path: std.Build.LazyPath, 22 | cgo_enabled: bool = true, 23 | }; 24 | 25 | /// Create a GoBuildStep 26 | pub fn create(b: *std.Build, options: Options) *BuildStep { 27 | const self = b.allocator.create(BuildStep) catch unreachable; 28 | self.* = .{ 29 | .opts = options, 30 | .generated_bin = null, 31 | .step = std.Build.Step.init(.{ 32 | .id = .custom, 33 | .name = "go build", 34 | .owner = b, 35 | .makeFn = BuildStep.make, 36 | }), 37 | }; 38 | return self; 39 | } 40 | 41 | pub fn make(step: *std.Build.Step, opts: std.Build.Step.MakeOptions) !void { 42 | const self: *BuildStep = @fieldParentPtr("step", step); 43 | const b = step.owner; 44 | var go_args = std.ArrayList([]const u8).init(b.allocator); 45 | defer go_args.deinit(); 46 | 47 | try go_args.append("go"); 48 | try go_args.append("build"); 49 | 50 | const output_file = try b.cache_root.join(b.allocator, &.{ "go", self.opts.name }); 51 | try go_args.appendSlice(&.{ "-o", output_file }); 52 | 53 | switch (self.opts.optimize) { 54 | .ReleaseSafe => try go_args.appendSlice(&.{ "-tags", "ReleaseSafe" }), 55 | .ReleaseFast => try go_args.appendSlice(&.{ "-tags", "ReleaseFast" }), 56 | .ReleaseSmall => try go_args.appendSlice(&.{ "-tags", "ReleaseSmall" }), 57 | .Debug => try go_args.appendSlice(&.{ "-tags", "Debug" }), 58 | } 59 | 60 | var env = try std.process.getEnvMap(b.allocator); 61 | 62 | // CGO 63 | if (self.opts.cgo_enabled) { 64 | try env.put("CGO_ENABLED", "1"); 65 | // Set zig as the CGO compiler 66 | const target = self.opts.target; 67 | const cc = b.fmt( 68 | "zig cc -target {s}-{s}-{s}", 69 | .{ @tagName(target.result.cpu.arch), @tagName(target.result.os.tag), @tagName(target.result.abi) }, 70 | ); 71 | try env.put("CC", cc); 72 | const cxx = b.fmt( 73 | "zig c++ -target {s}-{s}-{s}", 74 | .{ @tagName(target.result.cpu.arch), @tagName(target.result.os.tag), @tagName(target.result.abi) }, 75 | ); 76 | try env.put("CXX", cxx); 77 | try env.put("GOOS", @tagName(target.result.os.tag)); 78 | 79 | // Tell the linker we are statically linking 80 | go_args.appendSlice(&.{ "--ldflags", "-linkmode=external -extldflags=-static" }) catch @panic("OOM"); 81 | } else { 82 | try env.put("CGO_ENABLED", "0"); 83 | } 84 | 85 | // Output file always needs to be added last 86 | try go_args.append(self.opts.package_path.getPath(b)); 87 | 88 | const cmd = std.mem.join(b.allocator, " ", go_args.items) catch @panic("OOM"); 89 | const node = opts.progress_node.start(cmd, 1); 90 | defer node.end(); 91 | 92 | // run the command 93 | try self.evalChildProcess(go_args.items, &env); 94 | 95 | if (self.generated_bin == null) { 96 | const generated_bin = b.allocator.create(std.Build.GeneratedFile) catch unreachable; 97 | generated_bin.* = .{ .step = step }; 98 | self.generated_bin = generated_bin; 99 | } 100 | self.generated_bin.?.path = output_file; 101 | } 102 | 103 | /// Return the LazyPath of the generated binary 104 | pub fn getEmittedBin(self: *BuildStep) std.Build.LazyPath { 105 | if (self.generated_bin) |generated_bin| 106 | return .{ .generated = .{ .file = generated_bin } }; 107 | 108 | const b = self.step.owner; 109 | const generated_bin = b.allocator.create(std.Build.GeneratedFile) catch unreachable; 110 | generated_bin.* = .{ .step = &self.step }; 111 | self.generated_bin = generated_bin; 112 | return .{ .generated = .{ .file = generated_bin } }; 113 | } 114 | 115 | /// Add a run step which depends on the GoBuildStep 116 | pub fn addRunStep(self: *BuildStep) *std.Build.Step.Run { 117 | const b = self.step.owner; 118 | const run_step = std.Build.Step.Run.create(b, b.fmt("run {s}", .{self.opts.name})); 119 | run_step.step.dependOn(&self.step); 120 | const bin_file = self.getEmittedBin(); 121 | const arg: std.Build.Step.Run.PrefixedLazyPath = .{ .prefix = "", .lazy_path = bin_file }; 122 | run_step.argv.append(b.allocator, .{ .lazy_path = arg }) catch unreachable; 123 | return run_step; 124 | } 125 | 126 | // Add an install step which depends on the GoBuildStep 127 | pub fn addInstallStep(self: *BuildStep) void { 128 | const b = self.step.owner; 129 | const bin_file = self.getEmittedBin(); 130 | const install_step = b.addInstallBinFile(bin_file, self.opts.name); 131 | install_step.step.dependOn(&self.step); 132 | b.getInstallStep().dependOn(&install_step.step); 133 | } 134 | 135 | fn evalChildProcess(self: *BuildStep, argv: []const []const u8, env: *const std.process.EnvMap) !void { 136 | const s = &self.step; 137 | const arena = s.owner.allocator; 138 | 139 | try std.Build.Step.handleChildProcUnsupported(s, null, argv); 140 | try std.Build.Step.handleVerbose(s.owner, null, argv); 141 | 142 | const result = std.process.Child.run(.{ 143 | .allocator = arena, 144 | .argv = argv, 145 | .env_map = env, 146 | }) catch |err| return s.fail("unable to spawn {s}: {s}", .{ argv[0], @errorName(err) }); 147 | 148 | if (result.stderr.len > 0) { 149 | try s.result_error_msgs.append(arena, result.stderr); 150 | } 151 | 152 | try std.Build.Step.handleChildProcessTerm(s, result.term, null, argv); 153 | } 154 | }; 155 | -------------------------------------------------------------------------------- /build.zig.zon: -------------------------------------------------------------------------------- 1 | .{ 2 | .name = .go, 3 | .fingerprint = 0xb66893564b4db9cd, 4 | .version = "0.0.0", 5 | .dependencies = .{}, 6 | .paths = .{""}, 7 | } 8 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/rockorager/zig4go 2 | 3 | go 1.22.6 4 | --------------------------------------------------------------------------------