[Nickle]Syntax for tagged unions

Keith Packard keithp@keithp.com
Thu, 15 Mar 2001 19:49:27 -0800


I've got tagged unions working again; bart has convinced me that the pain 
is only syntactic, not semantic.  So, I need to fix the syntax problems, 
but that requires some thought.  Here's what I've got currently:

Declaration:

	typedef union {
		integer		value;
		string		name;
	} token;

They look like C unions to some extent, you can access the tagged types
directly:

	token	t;
	integer	v;
	string	n;

	t.value = 10;
	v = t.value;
	t.name = "hello world";
	n = t.name;

The system does tag checking when fetching the union value, if the tag 
doesn't match, a run-time exception is generated.

You can also 'construct' a union type from a compatible value:

	t = (token.value) 12;
	if (t == (token.name) "glorf")
		printf ("Hit glorf token\n");

Finally, you can branch on the tag name using the magic 'union switch' 
statement:

	union switch (t) {
	case name:
		printf ("Name %g\n", t.name);
		break;
	case value:
		printf ("Value %g\n", t.value);
		break;
	}

Obviously, these require a bit more typing than when using the pure 
polymorphic data type 'poly', but have the advantage of doing both
type checking and tag checking at runtime.

Questions:

+ Should I try to make the tag names usable inside the 'union switch' 
  statement?  This is pure sugar; the machine must still typecheck accesses 
  as external routines (or threads) may well modify which tag is in use.
  The only way to make this more "robust" is to capture the value at the 
  switch and have the tag names refer to the captured value.  That
  makes them much less useful; any stores will be lost outside of the 
  scope.

+ Should I change the constructor syntax?  It looks a lot like a C cast,
  which is kinda what it is.

Other comments?

-keith