Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Universal conversion to pointer #68

Closed
joelreymont opened this issue Oct 28, 2024 · 4 comments
Closed

Universal conversion to pointer #68

joelreymont opened this issue Oct 28, 2024 · 4 comments

Comments

@joelreymont
Copy link
Contributor

Assuming I have a recursive grammar that matches this AST

const BoolExprType = enum {
    defined_id,
    binary_expr,
    paren_expr,
    not_expr,
};

const BoolExpr = union(BoolExprType) {
    defined_id: []const u8,
    binary_expr: *BinaryBoolExpr,
    paren_expr: *BoolExpr,
    not_expr: *BoolExpr,
};

const BinaryBoolExpr = struct {
    lhs: BoolExpr,
    op: u8,
    rhs: BoolExpr,
};

Is there a universal conversion function that will return a pointer to whatever the parser returns, assuming parsing success?

@joelreymont
Copy link
Contributor Author

There's the approach with the conversion function in #51 but I like mecha.unionInit and would hate to create the union by hand like that ticket does.

@Hejsil
Copy link
Owner

Hejsil commented Oct 28, 2024

Is there a universal conversion function that will return a pointer to whatever the parser returns.

I assume you mean a function that will take an object and put it on the heap, giving you a pointer to that object. No, such a function does not exists currently

@joelreymont
Copy link
Contributor Author

joelreymont commented Oct 28, 2024 via email

@joelreymont joelreymont reopened this Oct 29, 2024
@joelreymont
Copy link
Contributor Author

This works!

Would it be a good addition to Mecha?

fn toPtr(comptime T: type) fn (std.mem.Allocator, T) anyerror!*T {
    return struct {
        fn toPtr(allocator: std.mem.Allocator, value: T) !*T {
            const result = try allocator.create(T);
            result.* = value;
            return result;
        }
    }.toPtr;
}

test "toPtr" {
    const allocator = testing.allocator;

    const Foo = struct {
        bar: u32,
        baz: u32,
    };

    const conv = toPtr(Foo);
    const value = Foo{ .bar = 10, .baz = 20 };
    const ptr = try conv(allocator, value);
    defer allocator.destroy(ptr);
    try testing.expectEqual(value, ptr.*);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants