4 ms·
No, no, no! This is terrible! variant_cast is just garbage. It relies on struct layout, and if anything has wider alignment than ptrdiff_t, it's broken. For e
by klodolph 9y ago
No, no, no! This is terrible!
variant_cast is just garbage. It relies on struct layout, and if anything has wider alignment than ptrdiff_t, it's broken.
For example, a double in 32-bit PowerPC has 64-bit alignment but ptrdiff_t is 32 bits, so the pointer is wrong. Maybe x64 you get away with it for most types (not all!), but can you raise your right hand and solemnly swear that you'll never ever want to port to a non-x64 system?
Additionally, all the explicit casting means that this has basically no type safety at all. I can a.tag = tag(SomeThree) even though SomeThree is not a member of a's type, and then I will be able to successfully let b = as(&a, SomeThree) and boom! I've just scribbled over memory without so much as a peep from the compiler. What is the of having tagged unions (a TYPE SAFETY FEATURE) if your tagged union implementation is LESS type safe than untagged unions?
This last point is actually a bit subtle… accessing the wrong member of a union is probably not what you want to do most of the time, but the language in the C standard is quite clear (see DR #257, language was clarified in C99 but present in earlier versions) and accessing the wrong union member just gives you whatever you stored in a union reinterpreted as whatever you read out of it. But this tagged union implementation lets you access a union member which doesn't even exist.
Let's not try to implement new language features on top of C with macros. It never ends well. Either figure out a way to live with a little boilerplate or use a different language, those are the only sane options.
- comex 9y agoIt's true that this implementation is wrong, but I disagree that it's a bad idea. Certainly it's possible to do correctly in various ways, e.g. by having the macro pass offsetof(Some, the_union) (but the existing code doesn't name the union and there would have to be consideration for multiple variant types).
- klodolph 9y ago"Certainly it's possible to do correctly in various ways" Not very convincing. At the very least, you'd need to pass in the type name as a macro parameter, use non-portable GCC extensions, or define some additional boilerplate for each union type. We can't just say "offsetof" and handwave the actual macro definition here. The traditional solution, to define an enum type, works reasonably. You can certainly get silent type errors from typos but perhaps we can tolerate the risk. It's not worse than, say, qsort in terms of type safety. The options I alluded to above are due to the fact that in order to allow the compiler to type-check for us, we need to keep the type of "x" passed in to "as()". You need to check the tag and either abort or return the correct union member. So "x" appears twice, but that's a bad idea for a macro. So you either use the GCC extension which allows statements as expressions, or you dispatch to a boilerplate function for each union type. I can't think of a different way to do things.
- comex 9y ago> Not very convincing. Sorry, I was in a hurry when I wrote that comment :) The easiest way is to take advantage of the fact that a pointer to a union can be casted to a pointer to one of its members (C11 6.7.2.1.16), or in other words that all the possible variants are at the same offset. So we can do: typedef struct Some variantof_SomeOne; #define as(x, T) ((struct T *)variant_cast(x, tag(T), \ offsetof(variantof_##T, u))) where the definition of Some would have to be changed to give the union field a name, and variant_cast would add the offset given as an argument. An alternative would be one of the options you mentioned, a boilerplate function. But it doesn't have to be 'real' boilerplate: it's possible to use macros to automate the definition of such functions. Given suitable macros, you can write something like: #define FOO_FIELDS(f) \ f(one, struct bar) \ f(two, float) \ f(three, int) DEFINE_VARIANT(foo, FOO_FIELDS) and get as much boilerplate as you want, like: enum foo_tag { foo_tag_one, foo_tag_two, foo_tag_three }; struct foo { enum foo_tag tag; union { struct bar one; float two; int three; }; }; static inline bool foo_is_one(struct foo *fo) { return foo->tag == foo_tag_one; } static inline struct bar * foo_get_one(struct foo *foo) { assert(foo->tag == foo_tag_one); return &foo->one; } [etc. for other variants]
- huhtenberg 9y agoI think it's an elegant piece of garbage actually. All your nitpicks are fairly easy to address. + union zee_tag { + ptrdiff_t tag; + max_align_t foo; + }; + struct Some { - ptrdiff_t tag; + zee_tag tag; > I can a.tag = tag(SomeThree) tag() just needs to take 'a' as another parameter and do a static_assert. > It relies on struct layout As in "ptrdiff_t needs to be the first member in a struct"? Oh, the horror. It's C, a language that generally expects you to know what you are doing. > all the explicit casting means that this has basically no type safety at all Duh. See above :) Generally speaking, you are missing a point here. This sort of contraption comes handy when the code needs to add a _bit_ more of invariant checking, but without going over the top. In comparison with a plain union this will help catching the misuse. Granted, it needs to be used correctly itself.
- klodolph 9y ago> As in "ptrdiff_t needs to be the first member in a struct"? Oh, the horror. It's C, a language that generally expects you to know what you are doing. Speaking of garbage, that's some really needless posturing. The comment was about the position of the second element in the structure, I suppose that this wasn't spelled out in the comment but everyone here knows that the first member of a struct is at the beginning. God forbid you would store __mm128i here, although generally that's an awful idea, it's not unreasonable to want to force 16-byte alignment or the like. > tag() just needs to take 'a' as another parameter and do a static_assert. Show me. I'm honestly curious what it would look like. > Generally speaking, you are missing a point here. This sort of contraption comes handy when the code needs to add a _bit_ more of invariant checking, but without going over the top. In comparison with a plain union this will help catching the misuse. Granted, it needs to be used correctly itself. Show me a version that adds invariant checking.
- huhtenberg 9y ago> The comment was about the position of the second element in the structure, I suppose that this wasn't spelled out in the comment but everyone here knows that the first member of a struct is at the beginning. Wit beyond measure, fascinating. union zee_tag { ptrdiff_t tag; max_align_t foo; }; static inline void * variant_cast(void * variant_ptr, ptrdiff_t desired_tag) { ptrdiff_t * variant_tag = (ptrdiff_t *)variant_ptr; assert(*variant_tag == desired_tag); - return (void *)((char *)variant_ptr + sizeof(ptrdiff_t)); + return (void *)((char *)variant_ptr + sizeof(union zee_tag)); } Shall I sprinkle some comments or is it OK this way? > Show me. @@ -15,6 +15,9 @@ #define is(x, T) ((x)->tag == tag(T)) #define as(x, T) ((struct T *)variant_cast((void *)(x), tag(T))) +#define union_field(T) struct T _##T +#define tag_union(x, T) (x)->tag = ((x)->_##T, (ptrdiff_t)&Tag##T) + struct SomeOne { int x; int y; @@ -25,17 +28,24 @@ float w; } TagSomeTwo; +struct SomeThree { + float zz; + float ww; +} TagSomeThree; + struct Some { ptrdiff_t tag; union { - struct SomeOne _; - struct SomeTwo __; + union_field( SomeOne ); + union_field( SomeTwo ); }; }; int main() { struct Some a = {}; - a.tag = tag(SomeTwo); + + tag_union(&a, SomeTwo); + tag_union(&a, SomeThree); printf("Is `a` tagged as SomeTwo: %d\n", is(&a, SomeTwo)); > Show me a version that adds invariant checking. An exercise left to the reader.
- wyufro 9y ago> It relies on struct layout, and if anything has wider alignment than ptrdiff_t, it's broken. I think you're wrong about this. I'm pretty certain a pointer to a struct is always equivilent to a pointer to the first member, except for the type. I went and looked it up in C11 (6.7.2.1 point 15): > A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning. Edit: A duh, the + sizeof(ptrdiff_t) is the part that's wrong. Yeah, agreed.
- rkangel 9y agoYes - this is what allows you to some semblance of struct inheritance. You can embed a structure as the first member in the 'derived' structure and then up and down cast as appropriate.
- jacquesm 9y ago> Let's not try to implement new language features on top of C with macros. Thank you for that. This happens though, in fact I've done it because the CEO of a company I worked for did not want to use anything but C and the project had a bunch of requirements that were very hard to meet with C. It's surprising how far you can get with that approach but in the end it is simply the wrong way to approach the problem. The right tool for the job is the best way to start any job.
- OskarS 9y agoI'm not a C programmer, but isn't there some directive you can add to a union to tightly pack it, or specify member memory locations or something? So that then you could guarantee that for the Some struct, `ptrdiff_t tag;` starts at offset 0 and the union starts at offset `sizeof(ptrdiff_t)`?
- clarry 9y agoThat doesn't help if your architecture doesn't support unaligned access. The compiler is allowed to insert padding for a good reason, and packing is rarely the right solution for anything.