diff options
| author | Andrew Kelley <andrew@ziglang.org> | 2020-12-28 20:15:00 -0700 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2020-12-28 20:15:17 -0700 |
| commit | bbe66572e1c1e2abff0a433c36291f3429482e8f (patch) | |
| tree | 6423d52cc29cc8ca91dc2cc954b3584a991fe0d1 | |
| parent | 7561fca4352e18f03fd4950591341150b9839fda (diff) | |
| download | zig-bbe66572e1c1e2abff0a433c36291f3429482e8f.tar.gz zig-bbe66572e1c1e2abff0a433c36291f3429482e8f.zip | |
stage2: C backend: handle string literals more gracefully
| -rw-r--r-- | src/codegen/c.zig | 40 |
1 files changed, 25 insertions, 15 deletions
diff --git a/src/codegen/c.zig b/src/codegen/c.zig index d949591a49..6f00992327 100644 --- a/src/codegen/c.zig +++ b/src/codegen/c.zig @@ -137,22 +137,32 @@ fn renderValue( ), }, .Array => { - // TODO first try specific tag representations for more efficiency - // Fall back to inefficient generic implementation. - try writer.writeAll("{"); - var index: usize = 0; - const len = t.arrayLen(); - const elem_ty = t.elemType(); - while (index < len) : (index += 1) { - if (index != 0) try writer.writeAll(","); - const elem_val = try val.elemValue(&ctx.arena.allocator, index); - try renderValue(ctx, writer, elem_ty, elem_val); - } - if (t.sentinel()) |sentinel_val| { - if (index != 0) try writer.writeAll(","); - try renderValue(ctx, writer, elem_ty, sentinel_val); + // First try specific tag representations for more efficiency. + switch (val.tag()) { + .undef, .empty_struct_value, .empty_array => try writer.writeAll("{}"), + .bytes => { + const bytes = val.cast(Value.Payload.Bytes).?.data; + // TODO: make our own C string escape instead of using {Z} + try writer.print("\"{Z}\"", .{bytes}); + }, + else => { + // Fall back to generic implementation. + try writer.writeAll("{"); + var index: usize = 0; + const len = t.arrayLen(); + const elem_ty = t.elemType(); + while (index < len) : (index += 1) { + if (index != 0) try writer.writeAll(","); + const elem_val = try val.elemValue(&ctx.arena.allocator, index); + try renderValue(ctx, writer, elem_ty, elem_val); + } + if (t.sentinel()) |sentinel_val| { + if (index != 0) try writer.writeAll(","); + try renderValue(ctx, writer, elem_ty, sentinel_val); + } + try writer.writeAll("}"); + }, } - try writer.writeAll("}"); }, else => |e| return ctx.fail(ctx.decl.src(), "TODO: C backend: implement value {s}", .{ @tagName(e), |
