From 0845cbe27783486feb5b4b57b2839326a2c86a6b Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Thu, 22 Feb 2018 17:53:58 +0100 Subject: [PATCH] name types inside functions after variable Before this commit: fn f() []const u8 { const S = struct {}; return @typeName(S); // "f()", unexpected. } And now: fn f() []const u8 { const S = struct {}; return @typeName(S); // "S", expected. } Fixes #675. --- src/ir.cpp | 6 ++++++ std/fmt/index.zig | 10 ++++------ test/cases/misc.zig | 17 +++++++++++++++++ 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index 7eac9e4d2..b276abff3 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -4172,7 +4172,13 @@ static IrInstruction *ir_gen_var_decl(IrBuilder *irb, Scope *scope, AstNode *nod buf_sprintf("cannot set section of local variable '%s'", buf_ptr(variable_declaration->symbol))); } + // Temporarily set the name of the IrExecutable to the VariableDeclaration + // so that the struct or enum from the init expression inherits the name. + Buf *old_exec_name = irb->exec->name; + irb->exec->name = variable_declaration->symbol; IrInstruction *init_value = ir_gen_node(irb, variable_declaration->expr, scope); + irb->exec->name = old_exec_name; + if (init_value == irb->codegen->invalid_instruction) return init_value; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 56b0add86..bd5b5710e 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -550,12 +550,6 @@ test "parse unsigned comptime" { } } -// Dummy field because of https://github.com/zig-lang/zig/issues/557. -// At top level because of https://github.com/zig-lang/zig/issues/675. -const Struct = struct { - unused: u8, -}; - test "fmt.format" { { var buf1: [32]u8 = undefined; @@ -588,6 +582,10 @@ test "fmt.format" { assert(mem.eql(u8, result, "u3: 5\n")); } { + // Dummy field because of https://github.com/zig-lang/zig/issues/557. + const Struct = struct { + unused: u8, + }; var buf1: [32]u8 = undefined; const value = Struct { .unused = 42, diff --git a/test/cases/misc.zig b/test/cases/misc.zig index 964c5babc..5e453fcbc 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -499,12 +499,29 @@ test "@canImplicitCast" { } test "@typeName" { + const Struct = struct { + }; + const Union = union { + unused: u8, + }; + const Enum = enum { + Unused, + }; comptime { assert(mem.eql(u8, @typeName(i64), "i64")); assert(mem.eql(u8, @typeName(&usize), "&usize")); + // https://github.com/zig-lang/zig/issues/675 + assert(mem.eql(u8, @typeName(TypeFromFn(u8)), "TypeFromFn(u8)")); + assert(mem.eql(u8, @typeName(Struct), "Struct")); + assert(mem.eql(u8, @typeName(Union), "Union")); + assert(mem.eql(u8, @typeName(Enum), "Enum")); } } +fn TypeFromFn(comptime T: type) type { + return struct {}; +} + test "volatile load and store" { var number: i32 = 1234; const ptr = (&volatile i32)(&number);