Skip to content

Commit fd213ac

Browse files
authored
Merge pull request #14462 from motiejus/infile_stdin
zig cc: support reading from stdin via "-x LANG -"
2 parents 40e8c22 + 233a0d3 commit fd213ac

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/Compilation.zig

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4597,6 +4597,27 @@ pub const FileExt = enum {
45974597
=> false,
45984598
};
45994599
}
4600+
4601+
pub fn canonicalName(ext: FileExt, target: Target) [:0]const u8 {
4602+
return switch (ext) {
4603+
.c => ".c",
4604+
.cpp => ".cpp",
4605+
.cu => ".cu",
4606+
.h => ".h",
4607+
.m => ".m",
4608+
.mm => ".mm",
4609+
.ll => ".ll",
4610+
.bc => ".bc",
4611+
.assembly => ".s",
4612+
.assembly_with_cpp => ".S",
4613+
.shared_library => target.dynamicLibSuffix(),
4614+
.object => target.ofmt.fileExt(target.cpu.arch),
4615+
.static_library => target.staticLibSuffix(),
4616+
.zig => ".zig",
4617+
.def => ".def",
4618+
.unknown => "",
4619+
};
4620+
}
46004621
};
46014622

46024623
pub fn hasObjectExt(filename: []const u8) bool {

src/main.zig

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3020,6 +3020,32 @@ fn buildOutputType(
30203020
break :l global_cache_directory;
30213021
};
30223022

3023+
for (c_source_files.items) |*src| {
3024+
if (!mem.eql(u8, src.src_path, "-")) continue;
3025+
3026+
const ext = src.ext orelse
3027+
fatal("-E or -x is required when reading from a non-regular file", .{});
3028+
3029+
// "-" is stdin. Dump it to a real file.
3030+
const sep = fs.path.sep_str;
3031+
const sub_path = try std.fmt.allocPrint(arena, "tmp" ++ sep ++ "{x}-stdin{s}", .{
3032+
std.crypto.random.int(u64), ext.canonicalName(target_info.target),
3033+
});
3034+
try local_cache_directory.handle.makePath("tmp");
3035+
// Note that in one of the happy paths, execve() is used to switch
3036+
// to clang in which case any cleanup logic that exists for this
3037+
// temporary file will not run and this temp file will be leaked.
3038+
// Oh well. It's a minor punishment for using `-x c` which nobody
3039+
// should be doing. Therefore, we make no effort to clean up. Using
3040+
// `-` for stdin as a source file always leaks a temp file.
3041+
var f = try local_cache_directory.handle.createFile(sub_path, .{});
3042+
defer f.close();
3043+
try f.writeFileAll(io.getStdIn(), .{});
3044+
3045+
// Convert `sub_path` to be relative to current working directory.
3046+
src.src_path = try local_cache_directory.join(arena, &.{sub_path});
3047+
}
3048+
30233049
if (build_options.have_llvm and emit_asm != .no) {
30243050
// LLVM has no way to set this non-globally.
30253051
const argv = [_][*:0]const u8{ "zig (LLVM option parsing)", "--x86-asm-syntax=intel" };

0 commit comments

Comments
 (0)