Commit 4420afe64d

LemonBoy <thatlemon@gmail.com>
2020-11-26 13:28:38
tests: Use {s} instead of {} when formatting strings
1 parent 1c13ca5
lib/std/special/build_runner.zig
@@ -98,7 +98,7 @@ pub fn main() !void {
                     return usageAndErr(builder, false, stderr_stream);
                 };
                 builder.color = std.meta.stringToEnum(@TypeOf(builder.color), next_arg) orelse {
-                    warn("expected [auto|on|off] after --color, found '{}'", .{next_arg});
+                    warn("expected [auto|on|off] after --color, found '{s}'", .{next_arg});
                     return usageAndErr(builder, false, stderr_stream);
                 };
             } else if (mem.eql(u8, arg, "--override-lib-dir")) {
@@ -126,7 +126,7 @@ pub fn main() !void {
                 builder.args = argsRest(args, arg_idx);
                 break;
             } else {
-                warn("Unrecognized argument: {}\n\n", .{arg});
+                warn("Unrecognized argument: {s}\n\n", .{arg});
                 return usageAndErr(builder, false, stderr_stream);
             }
         } else {
@@ -168,7 +168,7 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void
     }
 
     try out_stream.print(
-        \\Usage: {} build [steps] [options]
+        \\Usage: {s} build [steps] [options]
         \\
         \\Steps:
         \\
@@ -177,10 +177,10 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void
     const allocator = builder.allocator;
     for (builder.top_level_steps.items) |top_level_step| {
         const name = if (&top_level_step.step == builder.default_step)
-            try fmt.allocPrint(allocator, "{} (default)", .{top_level_step.step.name})
+            try fmt.allocPrint(allocator, "{s} (default)", .{top_level_step.step.name})
         else
             top_level_step.step.name;
-        try out_stream.print("  {s:<27} {}\n", .{ name, top_level_step.description });
+        try out_stream.print("  {s:<27} {s}\n", .{ name, top_level_step.description });
     }
 
     try out_stream.writeAll(
@@ -200,12 +200,12 @@ fn usage(builder: *Builder, already_ran_build: bool, out_stream: anytype) !void
         try out_stream.print("  (none)\n", .{});
     } else {
         for (builder.available_options_list.items) |option| {
-            const name = try fmt.allocPrint(allocator, "  -D{}=[{}]", .{
+            const name = try fmt.allocPrint(allocator, "  -D{s}=[{s}]", .{
                 option.name,
                 Builder.typeIdName(option.type_id),
             });
             defer allocator.free(name);
-            try out_stream.print("{s:<29} {}\n", .{ name, option.description });
+            try out_stream.print("{s:<29} {s}\n", .{ name, option.description });
         }
     }
 
test/src/compare_output.zig
@@ -97,7 +97,7 @@ pub const CompareOutputContext = struct {
 
         switch (case.special) {
             Special.Asm => {
-                const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {}", .{
+                const annotated_case_name = fmt.allocPrint(self.b.allocator, "assemble-and-link {s}", .{
                     case.name,
                 }) catch unreachable;
                 if (self.test_filter) |filter| {
@@ -116,7 +116,7 @@ pub const CompareOutputContext = struct {
             },
             Special.None => {
                 for (self.modes) |mode| {
-                    const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{
+                    const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s} ({s})", .{
                         "compare-output",
                         case.name,
                         @tagName(mode),
@@ -141,7 +141,7 @@ pub const CompareOutputContext = struct {
                 }
             },
             Special.RuntimeSafety => {
-                const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {}", .{case.name}) catch unreachable;
+                const annotated_case_name = fmt.allocPrint(self.b.allocator, "safety {s}", .{case.name}) catch unreachable;
                 if (self.test_filter) |filter| {
                     if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
                 }
test/src/run_translated_c.zig
@@ -77,7 +77,7 @@ pub const RunTranslatedCContext = struct {
     pub fn addCase(self: *RunTranslatedCContext, case: *const TestCase) void {
         const b = self.b;
 
-        const annotated_case_name = fmt.allocPrint(self.b.allocator, "run-translated-c {}", .{case.name}) catch unreachable;
+        const annotated_case_name = fmt.allocPrint(self.b.allocator, "run-translated-c {s}", .{case.name}) catch unreachable;
         if (self.test_filter) |filter| {
             if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
         }
@@ -92,13 +92,13 @@ pub const RunTranslatedCContext = struct {
                 .basename = case.sources.items[0].filename,
             },
         });
-        translate_c.step.name = b.fmt("{} translate-c", .{annotated_case_name});
+        translate_c.step.name = b.fmt("{s} translate-c", .{annotated_case_name});
         const exe = translate_c.addExecutable();
         exe.setTarget(self.target);
-        exe.step.name = b.fmt("{} build-exe", .{annotated_case_name});
+        exe.step.name = b.fmt("{s} build-exe", .{annotated_case_name});
         exe.linkLibC();
         const run = exe.run();
-        run.step.name = b.fmt("{} run", .{annotated_case_name});
+        run.step.name = b.fmt("{s} run", .{annotated_case_name});
         if (!case.allow_warnings) {
             run.expectStdErrEqual("");
         }
test/src/translate_c.zig
@@ -99,7 +99,7 @@ pub const TranslateCContext = struct {
         const b = self.b;
 
         const translate_c_cmd = "translate-c";
-        const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {}", .{ translate_c_cmd, case.name }) catch unreachable;
+        const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s}", .{ translate_c_cmd, case.name }) catch unreachable;
         if (self.test_filter) |filter| {
             if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
         }
test/tests.zig
@@ -482,7 +482,7 @@ pub fn addPkgTests(
     is_wasmtime_enabled: bool,
     glibc_dir: ?[]const u8,
 ) *build.Step {
-    const step = b.step(b.fmt("test-{}", .{name}), desc);
+    const step = b.step(b.fmt("test-{s}", .{name}), desc);
 
     for (test_targets) |test_target| {
         if (skip_non_native and !test_target.target.isNative())
@@ -523,7 +523,7 @@ pub fn addPkgTests(
 
         const these_tests = b.addTest(root_src);
         const single_threaded_txt = if (test_target.single_threaded) "single" else "multi";
-        these_tests.setNamePrefix(b.fmt("{}-{}-{}-{}-{} ", .{
+        these_tests.setNamePrefix(b.fmt("{s}-{s}-{s}-{s}-{s} ", .{
             name,
             triple_prefix,
             @tagName(test_target.mode),
@@ -570,7 +570,7 @@ pub const StackTracesContext = struct {
             const expect_for_mode = expect[@enumToInt(mode)];
             if (expect_for_mode.len == 0) continue;
 
-            const annotated_case_name = fmt.allocPrint(self.b.allocator, "{} {} ({})", .{
+            const annotated_case_name = fmt.allocPrint(self.b.allocator, "{s} {s} ({s})", .{
                 "stack-trace",
                 name,
                 @tagName(mode),
@@ -637,7 +637,7 @@ pub const StackTracesContext = struct {
             defer args.deinit();
             args.append(full_exe_path) catch unreachable;
 
-            warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });
+            warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name });
 
             const child = std.ChildProcess.init(args.items, b.allocator) catch unreachable;
             defer child.deinit();
@@ -650,7 +650,7 @@ pub const StackTracesContext = struct {
             if (b.verbose) {
                 printInvocation(args.items);
             }
-            child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });
+            child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) });
 
             const stdout = child.stdout.?.inStream().readAllAlloc(b.allocator, max_stdout_size) catch unreachable;
             defer b.allocator.free(stdout);
@@ -659,14 +659,14 @@ pub const StackTracesContext = struct {
             var stderr = stderrFull;
 
             const term = child.wait() catch |err| {
-                debug.panic("Unable to spawn {}: {}\n", .{ full_exe_path, @errorName(err) });
+                debug.panic("Unable to spawn {s}: {s}\n", .{ full_exe_path, @errorName(err) });
             };
 
             switch (term) {
                 .Exited => |code| {
                     const expect_code: u32 = 1;
                     if (code != expect_code) {
-                        warn("Process {} exited with error code {} but expected code {}\n", .{
+                        warn("Process {s} exited with error code {d} but expected code {d}\n", .{
                             full_exe_path,
                             code,
                             expect_code,
@@ -676,17 +676,17 @@ pub const StackTracesContext = struct {
                     }
                 },
                 .Signal => |signum| {
-                    warn("Process {} terminated on signal {}\n", .{ full_exe_path, signum });
+                    warn("Process {s} terminated on signal {d}\n", .{ full_exe_path, signum });
                     printInvocation(args.items);
                     return error.TestFailed;
                 },
                 .Stopped => |signum| {
-                    warn("Process {} stopped on signal {}\n", .{ full_exe_path, signum });
+                    warn("Process {s} stopped on signal {d}\n", .{ full_exe_path, signum });
                     printInvocation(args.items);
                     return error.TestFailed;
                 },
                 .Unknown => |code| {
-                    warn("Process {} terminated unexpectedly with error code {}\n", .{ full_exe_path, code });
+                    warn("Process {s} terminated unexpectedly with error code {d}\n", .{ full_exe_path, code });
                     printInvocation(args.items);
                     return error.TestFailed;
                 },
@@ -732,9 +732,9 @@ pub const StackTracesContext = struct {
                 warn(
                     \\
                     \\========= Expected this output: =========
-                    \\{}
+                    \\{s}
                     \\================================================
-                    \\{}
+                    \\{s}
                     \\
                 , .{ self.expect_output, got });
                 return error.TestFailed;
@@ -856,7 +856,7 @@ pub const CompileErrorContext = struct {
             zig_args.append("-O") catch unreachable;
             zig_args.append(@tagName(self.build_mode)) catch unreachable;
 
-            warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });
+            warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name });
 
             if (b.verbose) {
                 printInvocation(zig_args.items);
@@ -870,7 +870,7 @@ pub const CompileErrorContext = struct {
             child.stdout_behavior = .Pipe;
             child.stderr_behavior = .Pipe;
 
-            child.spawn() catch |err| debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });
+            child.spawn() catch |err| debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) });
 
             var stdout_buf = ArrayList(u8).init(b.allocator);
             var stderr_buf = ArrayList(u8).init(b.allocator);
@@ -879,7 +879,7 @@ pub const CompileErrorContext = struct {
             child.stderr.?.inStream().readAllArrayList(&stderr_buf, max_stdout_size) catch unreachable;
 
             const term = child.wait() catch |err| {
-                debug.panic("Unable to spawn {}: {}\n", .{ zig_args.items[0], @errorName(err) });
+                debug.panic("Unable to spawn {s}: {s}\n", .{ zig_args.items[0], @errorName(err) });
             };
             switch (term) {
                 .Exited => |code| {
@@ -889,7 +889,7 @@ pub const CompileErrorContext = struct {
                     }
                 },
                 else => {
-                    warn("Process {} terminated unexpectedly\n", .{b.zig_exe});
+                    warn("Process {s} terminated unexpectedly\n", .{b.zig_exe});
                     printInvocation(zig_args.items);
                     return error.TestFailed;
                 },
@@ -903,7 +903,7 @@ pub const CompileErrorContext = struct {
                     \\
                     \\Expected empty stdout, instead found:
                     \\================================================
-                    \\{}
+                    \\{s}
                     \\================================================
                     \\
                 , .{stdout});
@@ -926,7 +926,7 @@ pub const CompileErrorContext = struct {
                 if (!ok) {
                     warn("\n======== Expected these compile errors: ========\n", .{});
                     for (self.case.expected_errors.items) |expected| {
-                        warn("{}\n", .{expected});
+                        warn("{s}\n", .{expected});
                     }
                 }
             } else {
@@ -935,7 +935,7 @@ pub const CompileErrorContext = struct {
                         warn(
                             \\
                             \\=========== Expected compile error: ============
-                            \\{}
+                            \\{s}
                             \\
                         , .{expected});
                         ok = false;
@@ -947,7 +947,7 @@ pub const CompileErrorContext = struct {
             if (!ok) {
                 warn(
                     \\================= Full output: =================
-                    \\{}
+                    \\{s}
                     \\
                 , .{stderr});
                 return error.TestFailed;
@@ -1023,7 +1023,7 @@ pub const CompileErrorContext = struct {
     pub fn addCase(self: *CompileErrorContext, case: *const TestCase) void {
         const b = self.b;
 
-        const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {}", .{
+        const annotated_case_name = fmt.allocPrint(self.b.allocator, "compile-error {s}", .{
             case.name,
         }) catch unreachable;
         if (self.test_filter) |filter| {
@@ -1058,7 +1058,7 @@ pub const StandaloneContext = struct {
     pub fn addBuildFile(self: *StandaloneContext, build_file: []const u8) void {
         const b = self.b;
 
-        const annotated_case_name = b.fmt("build {} (Debug)", .{build_file});
+        const annotated_case_name = b.fmt("build {s} (Debug)", .{build_file});
         if (self.test_filter) |filter| {
             if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
         }
@@ -1079,7 +1079,7 @@ pub const StandaloneContext = struct {
 
         const run_cmd = b.addSystemCommand(zig_args.items);
 
-        const log_step = b.addLog("PASS {}\n", .{annotated_case_name});
+        const log_step = b.addLog("PASS {s}\n", .{annotated_case_name});
         log_step.step.dependOn(&run_cmd.step);
 
         self.step.dependOn(&log_step.step);
@@ -1089,7 +1089,7 @@ pub const StandaloneContext = struct {
         const b = self.b;
 
         for (self.modes) |mode| {
-            const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {} ({})", .{
+            const annotated_case_name = fmt.allocPrint(self.b.allocator, "build {s} ({s})", .{
                 root_src,
                 @tagName(mode),
             }) catch unreachable;
@@ -1103,7 +1103,7 @@ pub const StandaloneContext = struct {
                 exe.linkSystemLibrary("c");
             }
 
-            const log_step = b.addLog("PASS {}\n", .{annotated_case_name});
+            const log_step = b.addLog("PASS {s}\n", .{annotated_case_name});
             log_step.step.dependOn(&exe.step);
 
             self.step.dependOn(&log_step.step);
@@ -1172,7 +1172,7 @@ pub const GenHContext = struct {
             const self = @fieldParentPtr(GenHCmpOutputStep, "step", step);
             const b = self.context.b;
 
-            warn("Test {}/{} {}...", .{ self.test_index + 1, self.context.test_index, self.name });
+            warn("Test {d}/{d} {s}...", .{ self.test_index + 1, self.context.test_index, self.name });
 
             const full_h_path = self.obj.getOutputHPath();
             const actual_h = try io.readFileAlloc(b.allocator, full_h_path);
@@ -1182,9 +1182,9 @@ pub const GenHContext = struct {
                     warn(
                         \\
                         \\========= Expected this output: ================
-                        \\{}
+                        \\{s}
                         \\========= But found: ===========================
-                        \\{}
+                        \\{s}
                         \\
                     , .{ expected_line, actual_h });
                     return error.TestFailed;
@@ -1196,7 +1196,7 @@ pub const GenHContext = struct {
 
     fn printInvocation(args: []const []const u8) void {
         for (args) |arg| {
-            warn("{} ", .{arg});
+            warn("{s} ", .{arg});
         }
         warn("\n", .{});
     }
@@ -1232,7 +1232,7 @@ pub const GenHContext = struct {
         const b = self.b;
 
         const mode = builtin.Mode.Debug;
-        const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {} ({})", .{ case.name, @tagName(mode) }) catch unreachable;
+        const annotated_case_name = fmt.allocPrint(self.b.allocator, "gen-h {s} ({s})", .{ case.name, @tagName(mode) }) catch unreachable;
         if (self.test_filter) |filter| {
             if (mem.indexOf(u8, annotated_case_name, filter) == null) return;
         }
@@ -1253,7 +1253,7 @@ pub const GenHContext = struct {
 
 fn printInvocation(args: []const []const u8) void {
     for (args) |arg| {
-        warn("{} ", .{arg});
+        warn("{s} ", .{arg});
     }
     warn("\n", .{});
 }
build.zig
@@ -224,7 +224,7 @@ pub fn build(b: *Builder) !void {
 
     const opt_version_string = b.option([]const u8, "version-string", "Override Zig version string. Default is to find out with git.");
     const version = if (opt_version_string) |version| version else v: {
-        const version_string = b.fmt("{}.{}.{}", .{ zig_version.major, zig_version.minor, zig_version.patch });
+        const version_string = b.fmt("{d}.{d}.{d}", .{ zig_version.major, zig_version.minor, zig_version.patch });
 
         var code: u8 = undefined;
         const git_describe_untrimmed = b.execAllowFail(&[_][]const u8{
@@ -238,7 +238,7 @@ pub fn build(b: *Builder) !void {
             0 => {
                 // Tagged release version (e.g. 0.7.0).
                 if (!mem.eql(u8, git_describe, version_string)) {
-                    std.debug.print("Zig version '{}' does not match Git tag '{}'\n", .{ version_string, git_describe });
+                    std.debug.print("Zig version '{s}' does not match Git tag '{s}'\n", .{ version_string, git_describe });
                     std.process.exit(1);
                 }
                 break :v version_string;
@@ -258,15 +258,15 @@ pub fn build(b: *Builder) !void {
 
                 // Check that the commit hash is prefixed with a 'g' (a Git convention).
                 if (commit_id.len < 1 or commit_id[0] != 'g') {
-                    std.debug.print("Unexpected `git describe` output: {}\n", .{git_describe});
+                    std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe});
                     break :v version_string;
                 }
 
                 // The version is reformatted in accordance with the https://semver.org specification.
-                break :v b.fmt("{}-dev.{}+{}", .{ version_string, commit_height, commit_id[1..] });
+                break :v b.fmt("{s}-dev.{s}+{s}", .{ version_string, commit_height, commit_id[1..] });
             },
             else => {
-                std.debug.print("Unexpected `git describe` output: {}\n", .{git_describe});
+                std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe});
                 break :v version_string;
             },
         }
@@ -359,6 +359,195 @@ pub fn build(b: *Builder) !void {
     test_step.dependOn(docs_step);
 }
 
+fn dependOnLib(b: *Builder, lib_exe_obj: anytype, dep: LibraryDep) void {
+    for (dep.libdirs.items) |lib_dir| {
+        lib_exe_obj.addLibPath(lib_dir);
+    }
+    const lib_dir = fs.path.join(
+        b.allocator,
+        &[_][]const u8{ dep.prefix, "lib" },
+    ) catch unreachable;
+    for (dep.system_libs.items) |lib| {
+        const static_bare_name = if (mem.eql(u8, lib, "curses"))
+            @as([]const u8, "libncurses.a")
+        else
+            b.fmt("lib{s}.a", .{lib});
+        const static_lib_name = fs.path.join(
+            b.allocator,
+            &[_][]const u8{ lib_dir, static_bare_name },
+        ) catch unreachable;
+        const have_static = fileExists(static_lib_name) catch unreachable;
+        if (have_static) {
+            lib_exe_obj.addObjectFile(static_lib_name);
+        } else {
+            lib_exe_obj.linkSystemLibrary(lib);
+        }
+    }
+    for (dep.libs.items) |lib| {
+        lib_exe_obj.addObjectFile(lib);
+    }
+    for (dep.includes.items) |include_path| {
+        lib_exe_obj.addIncludeDir(include_path);
+    }
+}
+
+fn fileExists(filename: []const u8) !bool {
+    fs.cwd().access(filename, .{}) catch |err| switch (err) {
+        error.FileNotFound => return false,
+        else => return err,
+    };
+    return true;
+}
+
+fn addCppLib(b: *Builder, lib_exe_obj: anytype, cmake_binary_dir: []const u8, lib_name: []const u8) void {
+    lib_exe_obj.addObjectFile(fs.path.join(b.allocator, &[_][]const u8{
+        cmake_binary_dir,
+        "zigcpp",
+        b.fmt("{s}{s}{s}", .{ lib_exe_obj.target.libPrefix(), lib_name, lib_exe_obj.target.staticLibSuffix() }),
+    }) catch unreachable);
+}
+
+const LibraryDep = struct {
+    prefix: []const u8,
+    libdirs: ArrayList([]const u8),
+    libs: ArrayList([]const u8),
+    system_libs: ArrayList([]const u8),
+    includes: ArrayList([]const u8),
+};
+
+fn findLLVM(b: *Builder, llvm_config_exe: []const u8) !LibraryDep {
+    const shared_mode = try b.exec(&[_][]const u8{ llvm_config_exe, "--shared-mode" });
+    const is_static = mem.startsWith(u8, shared_mode, "static");
+    const libs_output = if (is_static)
+        try b.exec(&[_][]const u8{
+            llvm_config_exe,
+            "--libfiles",
+            "--system-libs",
+        })
+    else
+        try b.exec(&[_][]const u8{
+            llvm_config_exe,
+            "--libs",
+        });
+    const includes_output = try b.exec(&[_][]const u8{ llvm_config_exe, "--includedir" });
+    const libdir_output = try b.exec(&[_][]const u8{ llvm_config_exe, "--libdir" });
+    const prefix_output = try b.exec(&[_][]const u8{ llvm_config_exe, "--prefix" });
+
+    var result = LibraryDep{
+        .prefix = mem.tokenize(prefix_output, " \r\n").next().?,
+        .libs = ArrayList([]const u8).init(b.allocator),
+        .system_libs = ArrayList([]const u8).init(b.allocator),
+        .includes = ArrayList([]const u8).init(b.allocator),
+        .libdirs = ArrayList([]const u8).init(b.allocator),
+    };
+    {
+        var it = mem.tokenize(libs_output, " \r\n");
+        while (it.next()) |lib_arg| {
+            if (mem.startsWith(u8, lib_arg, "-l")) {
+                try result.system_libs.append(lib_arg[2..]);
+            } else {
+                if (fs.path.isAbsolute(lib_arg)) {
+                    try result.libs.append(lib_arg);
+                } else {
+                    var lib_arg_copy = lib_arg;
+                    if (mem.endsWith(u8, lib_arg, ".lib")) {
+                        lib_arg_copy = lib_arg[0 .. lib_arg.len - 4];
+                    }
+                    try result.system_libs.append(lib_arg_copy);
+                }
+            }
+        }
+    }
+    {
+        var it = mem.tokenize(includes_output, " \r\n");
+        while (it.next()) |include_arg| {
+            if (mem.startsWith(u8, include_arg, "-I")) {
+                try result.includes.append(include_arg[2..]);
+            } else {
+                try result.includes.append(include_arg);
+            }
+        }
+    }
+    {
+        var it = mem.tokenize(libdir_output, " \r\n");
+        while (it.next()) |libdir| {
+            if (mem.startsWith(u8, libdir, "-L")) {
+                try result.libdirs.append(libdir[2..]);
+            } else {
+                try result.libdirs.append(libdir);
+            }
+        }
+    }
+    return result;
+}
+
+fn configureStage2(b: *Builder, exe: anytype, ctx: Context, need_cpp_includes: bool) !void {
+    exe.addIncludeDir("src");
+    exe.addIncludeDir(ctx.cmake_binary_dir);
+    addCppLib(b, exe, ctx.cmake_binary_dir, "zigcpp");
+    assert(ctx.lld_include_dir.len != 0);
+    exe.addIncludeDir(ctx.lld_include_dir);
+    {
+        var it = mem.tokenize(ctx.lld_libraries, ";");
+        while (it.next()) |lib| {
+            exe.addObjectFile(lib);
+        }
+    }
+    {
+        var it = mem.tokenize(ctx.clang_libraries, ";");
+        while (it.next()) |lib| {
+            exe.addObjectFile(lib);
+        }
+    }
+    dependOnLib(b, exe, ctx.llvm);
+
+    // Boy, it sure would be nice to simply linkSystemLibrary("c++") and rely on zig's
+    // ability to provide libc++ right? Well thanks to C++ not having a stable ABI this
+    // will cause linker errors. It would work in the situation when `zig cc` is used to
+    // build LLVM, Clang, and LLD, however when depending on them as system libraries, system
+    // libc++ must be used.
+    const cross_compile = false; // TODO
+    if (cross_compile) {
+        // In this case we assume that zig cc was used to build the LLVM, Clang, LLD dependencies.
+        exe.linkSystemLibrary("c++");
+    } else {
+        if (exe.target.getOsTag() == .linux) {
+            // First we try to static link against gcc libstdc++. If that doesn't work,
+            // we fall back to -lc++ and cross our fingers.
+            addCxxKnownPath(b, ctx, exe, "libstdc++.a", "", need_cpp_includes) catch |err| switch (err) {
+                error.RequiredLibraryNotFound => {
+                    exe.linkSystemLibrary("c++");
+                },
+                else => |e| return e,
+            };
+
+            exe.linkSystemLibrary("pthread");
+        } else if (exe.target.isFreeBSD()) {
+            try addCxxKnownPath(b, ctx, exe, "libc++.a", null, need_cpp_includes);
+            exe.linkSystemLibrary("pthread");
+        } else if (exe.target.isDarwin()) {
+            if (addCxxKnownPath(b, ctx, exe, "libgcc_eh.a", "", need_cpp_includes)) {
+                // Compiler is GCC.
+                try addCxxKnownPath(b, ctx, exe, "libstdc++.a", null, need_cpp_includes);
+                exe.linkSystemLibrary("pthread");
+                // TODO LLD cannot perform this link.
+                // Set ZIG_SYSTEM_LINKER_HACK env var to use system linker ld instead.
+                // See https://github.com/ziglang/zig/issues/1535
+            } else |err| switch (err) {
+                error.RequiredLibraryNotFound => {
+                    // System compiler, not gcc.
+                    exe.linkSystemLibrary("c++");
+                },
+                else => |e| return e,
+            }
+        }
+
+        if (ctx.dia_guids_lib.len != 0) {
+            exe.addObjectFile(ctx.dia_guids_lib);
+        }
+    }
+}
+
 fn addCxxKnownPath(
     b: *Builder,
     ctx: CMakeConfig,
@@ -369,14 +558,14 @@ fn addCxxKnownPath(
 ) !void {
     const path_padded = try b.exec(&[_][]const u8{
         ctx.cxx_compiler,
-        b.fmt("-print-file-name={}", .{objname}),
+        b.fmt("-print-file-name={s}", .{objname}),
     });
     const path_unpadded = mem.tokenize(path_padded, "\r\n").next().?;
     if (mem.eql(u8, path_unpadded, objname)) {
         if (errtxt) |msg| {
-            warn("{}", .{msg});
+            warn("{s}", .{msg});
         } else {
-            warn("Unable to determine path to {}\n", .{objname});
+            warn("Unable to determine path to {s}\n", .{objname});
         }
         return error.RequiredLibraryNotFound;
     }