Hejsil / mecha

A parser combinator library for Zig
MIT License
473 stars 21 forks source link

Add toUnion converter and basic tests #64

Closed bigs closed 2 months ago

bigs commented 2 months ago

Closes #63.

Implements toUnion, a converter for use in map that will map to a substruct of a tagged union with the type of the union and an enum index into it.

Hejsil commented 2 months ago

Hmm thinking more on this, it seems this function does a little to much. It does what toStruct does and then puts that into a union field. How about we make the toUnion just take what it is mapping and assign it to a union field. Then converting to a union would be:

parser.map(toStruct(Struct)).map(toUnion(Union, .tag))

This would then also allow cases where the union field is not a struct:

mecha.int(.{}).map(toUnion(Union, .tag))
Hejsil commented 2 months ago

We could even call the function unionInit to match the name of the builtin function @unionInit as that is what the function would do.

bigs commented 2 months ago

Very reasonable! I'll make that change :)

bigs commented 2 months ago

@Hejsil Updated—much simpler, now! I did add a helper function to extract the type of a union's sub-struct. This is particularly useful for tagged unions with anonymous sub-struct types. If you feel this is extraneous, however, I will remove it!

Hejsil commented 2 months ago

I did add a helper function to extract the type of a union's sub-struct. This is particularly useful for tagged unions with anonymous sub-struct types. If you feel this is extraneous, however, I will remove it!

Let's not include that. Asking the user to give the struct a name seems reasonable to me

bigs commented 2 months ago

All set and fixed minor typo in the suggestion!

bigs commented 2 months ago

Should be in shape now!

Btw... I found mecha because I've written a lot of Haskell and OCaml and love parser combinators. One area where I feel like mecha is lacking a bit is in error messages. I'd love to hack on some improvements to that if that's something you're interesting or have thought about. Probably more work than I have time for, but would be happy to collab!

Hejsil commented 2 months ago

Merge here

Hejsil commented 2 months ago

Should be in shape now!

Btw... I found mecha because I've written a lot of Haskell and OCaml and love parser combinators. One area where I feel like mecha is lacking a bit is in error messages. I'd love to hack on some improvements to that if that's something you're interesting or have thought about. Probably more work than I have time for, but would be happy to collab!

If you have any good ideas open an issue for discussion :+1: