@@ -74,6 +74,13 @@ const AbstTree = struct {
for (self.children) |child| {
try w.print("{}", .{child});
}
try w.writeAll(
\\
\\ pub const Translate = AutoTranslate(@This());
\\ pub const translate = Translate.translate;
\\ pub const translateAlloc = Translate.translateAlloc;
\\
);
try w.writeAll("};\n");
} else {
comptime unreachable;
@@ -81,6 +88,36 @@ const AbstTree = struct {
}
};
fn AutoTranslate(into: type) type {
return struct {
pub const Self = @This();
pub const To: type = into;
pub const fields = @typeInfo(To).@"struct".fields;
pub fn translate(from: anytype) To {
const From = @TypeOf(from);
var result: To = undefined;
inline for (Self.fields) |field| {
if (!@hasField(From, field.name)) {
@compileError("Source struct " ++
@typeName(From) ++
" is missing required field '" ++ field.name ++
"' while translating into " ++
@typeName(To));
}
@field(result, field.name) = @field(from, field.name);
}
return result;
}
pub fn translateAlloc(a: std.mem.Allocator, from: anytype) !To {
_ = a;
_ = from;
comptime unreachable;
}
};
}
var root_tree: std.StringHashMapUnmanaged(*AbstTree) = .{};
pub fn main() !void {
@@ -98,8 +135,39 @@ pub fn main() !void {
var wfile = try wout_dir.createFile(std.fs.path.basename(wout_path.?), .{});
defer wfile.close();
try wfile.writeAll(
\\// Generated by srctree template compiler
\\//! Generated by srctree template compiler
\\
\\const std = @import("std");
\\
\\fn AutoTranslate(into: type) type {
\\ return struct {
\\ pub const Self = @This();
\\ pub const To: type = into;
\\ pub const fields = @typeInfo(To).@"struct".fields;
\\
\\ pub fn translate(from: anytype) To {
\\ const From = @TypeOf(from);
\\ var result: To = undefined;
\\ inline for (Self.fields) |field| {
\\ if (!@hasField(From, field.name)) {
\\ @compileError("Source struct " ++
\\ @typeName(From) ++
\\ " is missing required field '" ++ field.name ++
\\ "' while translating into " ++
\\ @typeName(To));
\\ }
\\ @field(result, field.name) = @field(from, field.name);
\\ }
\\ return result;
\\ }
\\
\\ pub fn translateAlloc(a: std.mem.Allocator, from: anytype) !To {
\\ _ = a;
\\ _ = from;
\\ comptime unreachable;
\\ }
\\ };
\\}
);
var wout = wfile.writer();