From 7083c120beda0a03d299c3a02981795f75bf28ad Mon Sep 17 00:00:00 2001 From: Melody Horn Date: Sat, 31 Oct 2020 23:38:05 -0600 Subject: explain tagged unions i forgot not everybody's been up to their chest in the C spec for the last two months --- language/type-definition.rst | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/language/type-definition.rst b/language/type-definition.rst index 88c4a04..327fb4d 100644 --- a/language/type-definition.rst +++ b/language/type-definition.rst @@ -32,7 +32,13 @@ Defining Types UnionBodySet <- CaseSpecifier+ (VariableDeclaration / ';') A robust union, or simply union, in Crowbar is what is known more broadly as a tagged union. - The top-level variable declaration must have a type which is some ``enum``, and its name must be the same as the identifier in the ``switch``. + It's a way to package some data alongside an ``enum`` but have the type of data depend on the value of the ``enum``. + Since the enum value indicates which data is present, the enum value is also known as a *tag*. + The top-level variable declaration creates the tag. + The tag must have a type which is some ``enum``. + The ``switch`` parameter must be the name of the tag, and the cases will declare the data associated with a given value of the tag. + This allows for storing extra data alongside enum values while using minimal additional space in memory. + (All the fields under the ``switch`` overlap as stored in memory, so it's important to use the tag to specify which field is available.) For example:: @@ -62,8 +68,8 @@ Defining Types .. crowbar:element:: FragileUnionDefinition <- 'fragile' 'union' identifier '{' VariableDeclaration+ '}' - A fragile union, like a struct, is a simple bag of fields. - However, unlike a struct, only the most recently assigned field is valid at any given time. + A fragile union also allows for storing one of several different types of data. + However, there is no internal indication of which type of data is actually being stored in the union. As such, in non-trivial cases no compiler can predict which field is or is not valid, and any statement which reads a field of a fragile union must itself be a :crowbar:ref:`FragileStatement`. .. todo:: -- cgit v1.2.3