Merge pull request #11122 from mitchellh/anon-has-field
stage2: @hasField for anon structs
This commit is contained in:
@@ -7790,6 +7790,15 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
|
||||
if (mem.eql(u8, field_name, "len")) break :hf true;
|
||||
break :hf false;
|
||||
}
|
||||
if (ty.castTag(.anon_struct)) |pl| {
|
||||
break :hf for (pl.data.names) |name| {
|
||||
if (mem.eql(u8, name, field_name)) break true;
|
||||
} else false;
|
||||
}
|
||||
if (ty.isTuple()) {
|
||||
const field_index = std.fmt.parseUnsigned(u32, field_name, 10) catch break :hf false;
|
||||
break :hf field_index < ty.structFieldCount();
|
||||
}
|
||||
break :hf switch (ty.zigTypeTag()) {
|
||||
.Struct => ty.structFields().contains(field_name),
|
||||
.Union => ty.unionFields().contains(field_name),
|
||||
|
||||
@@ -34,4 +34,16 @@ test "@hasField" {
|
||||
try expect(@hasField(enm, "b") == true);
|
||||
try expect(@hasField(enm, "non-existant") == false);
|
||||
try expect(@hasField(enm, "nope") == false);
|
||||
|
||||
const anon = @TypeOf(.{ .a = 1 });
|
||||
try expect(@hasField(anon, "a") == true);
|
||||
try expect(@hasField(anon, "b") == false);
|
||||
|
||||
const tuple = @TypeOf(.{ 1, 2 });
|
||||
try expect(@hasField(tuple, "a") == false);
|
||||
try expect(@hasField(tuple, "b") == false);
|
||||
try expect(@hasField(tuple, "0") == true);
|
||||
try expect(@hasField(tuple, "1") == true);
|
||||
try expect(@hasField(tuple, "2") == false);
|
||||
try expect(@hasField(tuple, "9999999999999999999999999") == false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user