Debian Codegraph @

documentation/manual/directives/union.yo

raw
1 Syntax: bf(%union) tt(union-definition body)
2
3 In the grammars of many programs different types of data are used for different
4 terminal and nonterminal tokens. For example, a numeric constant may
5 need type tt(int) or tt(double), while a string needs type tt(std::string),
6 and an identifier might need a pointer to an entry in a symbol table.
7
8 Traditionally, the tt(%union) directive has always been used to accomplish
9 this. The directive defines a bf(C) union-type whose fields specify one or
10 more data types for semantic values. The directive tt(%union) is followed by a
11 pair of braces containing one or more field definitions. For example:
12 verb(
13 %union {
14 double u_val;
15 symrec *u_tptr;
16 };
17 )
18 In this example the two fields represent a tt(double) and a tt(symrec
19 *). The associated field names are tt(u_val) and tt(u_tptr), which are used in
20 the tt(%token) and tt(%type) directives to specify types that are associated
21 with terminal or nonterminal symbols (see section ref(TYPE)).
22
23 Notes:
24 itemization(
25 it() The semicolon following the closing brace is em(optional).
26 it() Since bf(C++-11) class types can be used in tt(union)
27 definitions; they can also be used when defining b()'s tt(%union)
28 directives. When a class type variant is required, all required
29 constructors, the destructor and other members (like overloaded
30 assignment operators) must be able to handle the actual class type
31 data fields properly. A discussion of how to use unrestricted unions
32 is beyon this manual's scope, but can be found, e.g., in the url(C++
33 Annotations)(http://cppannotations.sf.net). See also section
34 ref(SEMANTICS).
35 it() The tt(%union) directive is also a bit of an anachronism. In many
36 situations using tt(%polymorphic) is more attractive than using
37 tt(%union) (cf. section ref(POLYMORPHIC)).
38 )
39
40 Although the tt(%union) directive is still supported by b(), its use is
41 largely superseded by the newer tt(%polymorphic) directive, allowing b() and
42 the bf(C++) compiler to verify that the correct types are used when semantic
43 values are assigned or retrieved, which, in turn, helps preventing run-time
44 errors.
45
46 tt(%stype, %union) and tt(%polymorphic) are mutually exclusive: only one
47 of these directives can be used.