Commit 0845cbe277

Ben Noordhuis <info@bnoordhuis.nl>
2018-02-22 17:53:58
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.
1 parent 884b5fb
Changed files (3)
src
std
test
cases
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;
 
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,
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);