authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2023-03-04 13:21:11+00:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-03-21 15:04:39+02:00
logf9b5829508e4f9a7e2eee2f05f58a38c00318d91
treed56e7826469317dfebe7d7c87fa58071b1d38546
parent5e161c102d4a99be4903d0074ea2513ebcdb985b

Sema: implement @export for arbitrary values


2 files changed, 36 insertions(+), 1 deletions(-)

src/Sema.zig+17-1
......@@ -5668,7 +5668,15 @@ fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
56685668 };
56695669 const decl_index = switch (operand.val.tag()) {
56705670 .function => operand.val.castTag(.function).?.data.owner_decl,
5671 else => return sema.fail(block, operand_src, "TODO implement exporting arbitrary Value objects", .{}), // TODO put this Value into an anonymous Decl and then export it.
5671 else => blk: {
5672 var anon_decl = try block.startAnonDecl();
5673 defer anon_decl.deinit();
5674 break :blk try anon_decl.finish(
5675 try operand.ty.copy(anon_decl.arena()),
5676 try operand.val.copy(anon_decl.arena()),
5677 0,
5678 );
5679 },
56725680 };
56735681 try sema.analyzeExport(block, src, options, decl_index);
56745682}
......@@ -5704,6 +5712,14 @@ pub fn analyzeExport(
57045712 return sema.failWithOwnedErrorMsg(msg);
57055713 }
57065714
5715 // TODO: some backends might support re-exporting extern decls
5716 if (exported_decl.isExtern()) {
5717 return sema.fail(block, src, "export target cannot be extern", .{});
5718 }
5719
5720 // This decl is alive no matter what, since it's being exported
5721 mod.markDeclAlive(exported_decl);
5722
57075723 const gpa = mod.gpa;
57085724
57095725 try mod.decl_exports.ensureUnusedCapacity(gpa, 1);
test/behavior/export.zig+19
......@@ -70,3 +70,22 @@ test "exporting using field access" {
7070
7171 _ = S.Inner.x;
7272}
73
74test "exporting comptime-known value" {
75 const x: u32 = 10;
76 @export(x, .{ .name = "exporting_comptime_known_value_foo" });
77 const S = struct {
78 extern const exporting_comptime_known_value_foo: u32;
79 };
80 try expect(S.exporting_comptime_known_value_foo == 10);
81}
82
83test "exporting comptime var" {
84 comptime var x: u32 = 5;
85 @export(x, .{ .name = "exporting_comptime_var_foo" });
86 x = 7; // modifying this now shouldn't change anything
87 const S = struct {
88 extern const exporting_comptime_var_foo: u32;
89 };
90 try expect(S.exporting_comptime_var_foo == 5);
91}