source: doc/theses/jiada_liang_MMath/intro.tex @ 48b76d03

Last change on this file since 48b76d03 was 48b76d03, checked in by Peter A. Buhr <pabuhr@…>, 5 months ago

fine tune justification for enumerations

  • Property mode set to 100644
File size: 9.8 KB
Line 
1\chapter{Introduction}
2
3All types in a programming language must have a set of constants, and these constants have primary names, \eg integral types have constants @-1@, @17@, @12345@, \etc.
4Constants can be overloaded among types, \eg @0@ is a null pointer for all pointer types, and the value zero for integral and floating-point types.
5Hence, each primary constant has a symbolic name referring to its internal representation, and these names are dictated by language syntax related to types.
6In theory, there are an infinite set of primary names per type.
7
8Secondary naming is a common practice in mathematics and engineering, \eg $\pi$, $\tau$ (2$\pi$), $\phi$ (golden ratio), MHz (1E6), and in general situations, \eg specific times (noon, New Years), cities (Big Apple), flowers (Lily), \etc.
9Many programming languages capture this important software-engineering capability through a mechanism called \Newterm{constant} or \Newterm{literal} naming, where a secondary name is aliased to a primary name.
10In some cases, secondary naming is \Newterm{pure}, where the matching internal representation can be chosen arbitrarily, and only equality operations are available, \eg @O_RDONLY@, @O_WRONLY@, @O_CREAT@, @O_TRUNC@, @O_APPEND@.
11Because a secondary name is a constant, it cannot appear in a mutable context, \eg \mbox{$\pi$ \lstinline{= 42}} is meaningless, and a constant has no address, \ie it is an \Newterm{rvalue}\footnote{
12The term rvalue defines an expression that can only appear on the right-hand side of an assignment expression.}.
13
14Secondary names can form an (ordered) set, \eg days of the week, months of a year, floors of a building (basement, ground, 1st), colours in a rainbow, \etc.
15Many programming languages capture these groupings through a mechanism called an \Newterm{enumeration}.
16\begin{quote}
17enumerate (verb, transitive).
18To count, ascertain the number of;
19\emph{more
20usually, to mention (a number of things or persons) separately, as if for the
21purpose of counting};
22to specify as in a list or catalogue.~\cite{OED}
23\end{quote}
24Within an enumeration set, the enumeration names must be unique, and instances of an enumerated type are restricted to its secondary names.
25It is possible to enumerate among set names without having an ordering among the set elements.
26For example, the week, the weekdays, the weekend, and every second day of the week.
27\begin{cfa}[morekeywords={in}]
28for ( cursor in Mon, Tue, Wed, Thu, Fri, Sat, Sun } ... $\C[3.75in]{// week}$
29for ( cursor in Mon, Tue, Wed, Thu, Fri } ...   $\C{// weekday}$
30for ( cursor in Thu, Fri } ...                                  $\C{// weekend}$
31for ( cursor in Mon, Wed, Fri, Sun } ...                $\C{// every second day of week}\CRT$
32\end{cfa}
33This independence from internal representation allows multiple names to have the same representation (eight note, quaver), giving synonyms.
34A set can have a partial or total ordering, making it possible to compare set elements, \eg Monday is before Friday and Friday is after.
35Ordering allows iterating among the enumeration set using relational operators and advancement, \eg
36\begin{cfa}
37for ( cursor = Monday; cursor @<=@ Friday; cursor = @succ@( cursor ) ) ...
38\end{cfa}
39Here the internal representations for the secondary names are \emph{generated} rather than listing a subset of names.
40
41
42\section{Terminology}
43
44The term \Newterm{enumeration} defines the set of secondary names, and the term \Newterm{enumerator} represents an arbitrary secondary name.
45As well, an enumerated type has three fundamental properties, \Newterm{label}, \Newterm{order}, and \Newterm{value}.
46\begin{cquote}
47\sf\setlength{\tabcolsep}{3pt}
48\begin{tabular}{rcccccccr}
49\it\color{red}enumeration       & \multicolumn{8}{c}{\it\color{red}enumerators} \\
50$\downarrow$\hspace*{25pt}      & \multicolumn{8}{c}{$\downarrow$}                              \\
51@enum@ Weekday \{                       & Mon,  & Tue,  & Wed,  & Thu,  & Fri,  & Sat,  & Sun = 42      & \};   \\
52\it\color{red}label                     & Mon   & Tue   & Wed   & Thu   & Fri   & Sat   & Sun           &               \\
53\it\color{red}order                     & 0             & 1             & 2             & 3             & 4             & 5             & 6                     &               \\
54\it\color{red}value                     & 0             & 1             & 2             & 3             & 4             & 5             & 42            &
55\end{tabular}
56\end{cquote}
57Here, the enumeration @Weekday@ defines the enumerator labels @Mon@, @Tue@, @Wed@, @Thu@, @Fri@, @Sat@ and @Sun@.
58The implicit ordering implies the successor of @Tue@ is @Mon@ and the predecessor of @Tue@ is @Wed@, independent of any associated enumerator values.
59The value is the constant represented by the secondary name, which can be implicitly or explicitly set.
60
61Specifying complex ordering is possible:
62\begin{cfa}
63enum E1 { $\color{red}[\(_1\)$ {A, B}, $\color{blue}[\(_2\)$ C $\color{red}]\(_1\)$, {D, E} $\color{blue}]\(_2\)$ }; $\C{// overlapping square brackets}$
64enum E2 { {A, {B, C} }, { {D, E}, F };  $\C{// nesting}$
65\end{cfa}
66For @E1@, there is the partial ordering among @A@, @B@ and @C@, and @C@, @D@ and @E@, but not among @A@, @B@ and @D@, @E@.
67For @E2@, there is the total ordering @A@ $<$ @{B, C}@ $<$ @{D, E}@ $<$ @F@.
68Only flat total-ordering among enumerators is considered in this work.
69
70
71\section{Motivation}
72
73Some programming languages only provide secondary renaming, which can be simulated by an enumeration without ordering.
74\begin{cfa}
75const Size = 20, Pi = 3.14159;
76enum { Size = 20, Pi = 3.14159 };   // unnamed enumeration $\(\Rightarrow\)$ no ordering
77\end{cfa}
78In both cases, it is possible to compare the secondary names, \eg @Size < Pi@, if that is meaningful;
79however, without an enumeration type-name, it is impossible to create an iterator cursor.
80
81Secondary renaming can similate an enumeration, but with extra effort.
82\begin{cfa}
83const Mon = 1, Tue = 2, Wed = 3, Thu = 4, Fri = 5, Sat = 6, Sun = 7;
84\end{cfa}
85Furthermore, reordering the enumerators requires manual renumbering.
86\begin{cfa}
87const Sun = 1, Mon = 2, Tue = 3, Wed = 4, Thu = 5, Fri = 6, Sat = 7;
88\end{cfa}
89Finally, there is no common type to create a type-checked instance or iterator cursor.
90Hence, there is only a weak equivalence between secondary naming and enumerations, justifying the enumeration type in a programming language.
91
92A variant (algebraic) type is often promoted as a kind of enumeration, \ie a varient type can simulate an enumeration.
93A variant type is a tagged-union, where the possible types may be heterogeneous.
94\begin{cfa}
95@variant@ Variant {
96        @int tag;@  // optional/implicit: 0 => int, 1 => double, 2 => S
97        @union {@ // implicit
98                case int i;
99                case double d;
100                case struct S { int i, j; } s;
101        @};@
102};
103\end{cfa}
104Crucially, the union implies instance storage is shared by all of the variant types.
105Hence, a variant is dynamically typed, as in a dynamic-typed programming-language, but the set of types is statically bound, similar to some aspects of dynamic gradual-typing~\cite{Gradual Typing}.
106Knowing which type is in a variant instance is crucial for correctness.
107Occasionally, it is possible to statically determine, all regions where each variant type is used, so a tag and runtime checking is unnecessary;
108otherwise, a tag is required to denote the particular type in the variant and the tag checked at runtime using some form of type pattern-matching.
109
110The tag can be implicitly set by the compiler on assignment, or explicitly set by the program\-mer.
111Type pattern-matching is then used to dynamically test the tag and branch to a section of code to safely manipulate the value, \eg:
112\begin{cfa}[morekeywords={match}]
113Variant v = 3// implicitly set tag to 0
114@match@( v ) {    // know the type or test the tag
115        case int { /* only access i field in v */ }
116        case double { /* only access d field in v */ }
117        case S { /* only access s field in v */ }
118}
119\end{cfa}
120For safety, either all variant types must be listed or a @default@ case must exist with no field accesses.
121
122To simulate an enumeration with a variant, the tag is re-purposed for either ordering or value and the variant types are omitted.
123\begin{cfa}
124variant Weekday {
125        int tag; // implicit 0 => Mon, ..., 6 => Sun
126        @case Mon;@ // no type
127        ...
128        @case Sun;@
129};
130\end{cfa}
131The type system ensures tag setting and testing are correct.
132However, the enumeration operations are limited to the available tag operations, \eg pattern matching.
133\begin{cfa}
134Weekday weekday = Mon;
135if ( @dynamic_cast(Mon)@weekday ) ... // test tag == Mon
136\end{cfa}
137While enumerating among tag names is possible:
138\begin{cfa}[morekeywords={in}]
139for ( cursor in Mon, Wed, Fri, Sun ) ...
140\end{cfa}
141ordering for iteration would require a \emph{magic} extension, such as a special @enum@ variant, because it has no meaning for a regular variant, \ie @int@ < @double@.
142
143However, if a special @enum@ variant allows the tags to be heterogeneously typed, ordering must fall back on case positioning, as many types have incomparable values.
144Iterating using tag ordering and heterogeneous types, also requires pattern matching.
145\begin{cfa}
146for ( cursor = Mon; cursor <= Fri; cursor = succ( cursor) ) {
147        switch( cursor ) {
148                case Mon { /* access special type for Mon */ }
149                ...
150                case Fri { /* access special type for Fri */ }
151        }
152}
153\end{cfa}
154If the variant type adds/removes types or the loop range changes, the pattern matching must be adjusted.
155As well, if the start/stop values are dynamic, it is impossible to statically determine if all variant types are listed.
156
157Forcing the notion of enumerating into variant types is ill formed and confusing.
158Hence, there is only a weak equivalence between an enumeration and variant type, justifying the enumeration type in a programming language.
159
160
161\section{Contributions}
162
163The goal of this work is to to extend the simple and unsafe enumeration type in the C programming-language into a sophisticated and safe type in the \CFA programming-language, while maintain backwards compatibility with C.
164On the surface, enumerations seem like a simple type.
165However, when extended with advanced features, enumerations become complex for both the type system and the implementation.
166
167\begin{enumerate}
168\item
169overloading
170\item
171scoping
172\item
173typing
174\item
175subset
176\item
177inheritance
178\end{enumerate}
Note: See TracBrowser for help on using the repository browser.