aboutsummaryrefslogtreecommitdiff
path: root/language
diff options
context:
space:
mode:
authorMelody Horn <melody@boringcactus.com>2020-10-31 23:38:05 -0600
committerMelody Horn <melody@boringcactus.com>2020-10-31 23:38:05 -0600
commit7083c120beda0a03d299c3a02981795f75bf28ad (patch)
tree6fb9b2455f57ba199331509f89d3c01b640159b2 /language
parent14c4550aff926f53f256e831a7d99bffffd21dfd (diff)
downloadspec-7083c120beda0a03d299c3a02981795f75bf28ad.tar.gz
spec-7083c120beda0a03d299c3a02981795f75bf28ad.zip
explain tagged unions
i forgot not everybody's been up to their chest in the C spec for the last two months
Diffstat (limited to 'language')
-rw-r--r--language/type-definition.rst12
1 files 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::