fix: make conditional fields optional using @hasField

Templates can now use 'if error' or similar conditionals without
requiring the caller to always provide those fields in the data struct.
This commit is contained in:
2026-01-23 12:10:48 +05:30
parent 4f1dcf3640
commit 53f147f5c4
3 changed files with 15 additions and 4 deletions

View File

@@ -1254,7 +1254,18 @@ const Compiler = struct {
// Regular field access - use buildAccessor for consistency
var accessor_buf: [512]u8 = undefined;
const accessor = self.buildAccessor(cond, &accessor_buf);
try self.writer.print("truthy({s})", .{accessor});
// Check if this is a simple top-level field access (no dots, not a loop var or mixin param)
const is_simple_field = std.mem.indexOfScalar(u8, cond, '.') == null and
!self.isLoopVar(cond) and !self.isMixinParam(cond);
if (is_simple_field) {
// Use @hasField to make the field optional at compile time
self.uses_data = true;
try self.writer.print("@hasField(@TypeOf(d), \"{s}\") and truthy({s})", .{ cond, accessor });
} else {
try self.writer.print("truthy({s})", .{accessor});
}
}
fn emitEach(self: *Compiler, e: ast.Each) anyerror!void {