source: doc/theses/mike_brooks_MMath/background.tex @ d3a49864

Last change on this file since d3a49864 was d3a49864, checked in by Peter A. Buhr <pabuhr@…>, 7 weeks ago

work on Figure 2.1

  • Property mode set to 100644
File size: 20.8 KB
Line 
1\chapter{Background}
2
3Since this work builds on C, it is necessary to explain the C mechanisms and their shortcomings for array, linked list, and string,
4
5
6\section{Array}
7
8At the start, the C programming language made a significant design mistake.
9\begin{quote}
10In C, there is a strong relationship between pointers and arrays, strong enough that pointers and arrays really should be treated simultaneously.
11Any operation which can be achieved by array subscripting can also be done with pointers.~\cite[p.~93]{C:old}
12\end{quote}
13Accessing any storage requires pointer arithmetic, even if it is just base-displacement addressing in an instruction.
14The conjoining of pointers and arrays could also be applied to structures, where a pointer references a structure field like an array element.
15Finally, while subscripting involves pointer arithmetic (as does field references @x.y.z@), it is very complex for multi-dimensional arrays and requires array descriptors to know stride lengths along dimensions.
16Many C errors result from performing pointer arithmetic instead of using subscripting.
17Some C textbooks erroneously teach pointer arithmetic suggesting it is faster than subscripting.
18
19C semantics want a programmer to \emph{believe} an array variable is a ``pointer to its first element.''
20This desire becomes apparent by a detailed inspection of an array declaration.
21\lstinput{34-34}{bkgd-carray-arrty.c}
22The inspection begins by using @sizeof@ to provide definite program semantics for the intuition of an expression's type.
23\lstinput{35-36}{bkgd-carray-arrty.c}
24Now consider the sizes of expressions derived from @ar@, modified by adding ``pointer to'' and ``first element'' (and including unnecessary parentheses to avoid confusion about precedence).
25\lstinput{37-40}{bkgd-carray-arrty.c}
26Given the size of @float@ is 4, the size of @ar@ with 10 floats being 40 bytes is common reasoning for C programmers.
27Equally, C programmers know the size of a \emph{pointer} to the first array element is 8 (or 4 depending on the addressing architecture).
28% Now, set aside for a moment the claim that this first assertion is giving information about a type.
29Clearly, an array and a pointer to its first element are different things.
30
31In fact, the idea that there is such a thing as a pointer to an array may be surprising and it is not the same thing as a pointer to the first element.
32\lstinput{42-45}{bkgd-carray-arrty.c}
33The first assignment gets
34\begin{cfa}
35warning: assignment to `float (*)[10]' from incompatible pointer type `float *'
36\end{cfa}
37and the second assignment gets the opposite.
38
39The inspection now refutes any suggestion that @sizeof@ is informing about allocation rather than type information.
40Note, @sizeof@ has two forms, one operating on an expression and the other on a type.
41Using the type form yields the same results as the prior expression form.
42\lstinput{46-49}{bkgd-carray-arrty.c}
43The results are also the same when there is \emph{no allocation} using a pointer-to-array type.
44\lstinput{51-57}{bkgd-carray-arrty.c}
45Hence, in all cases, @sizeof@ is informing about type information.
46
47So, thinking of an array as a pointer to its first element is too simplistic an analogue and it is not backed up by the type system.
48This misguided analogue works for a single-dimension array but there is no advantage other than possibly teaching beginning programmers about basic runtime array-access.
49
50Continuing, a short form for declaring array variables exists using length information provided implicitly by an initializer.
51\lstinput{59-62}{bkgd-carray-arrty.c}
52The compiler counts the number of initializer elements and uses this value as the first dimension.
53Unfortunately, the implicit element counting does not extend to dimensions beyond the first.
54\lstinput{64-67}{bkgd-carray-arrty.c}
55
56My contribution is recognizing:
57\begin{itemize}
58        \item There is value in using a type that knows its size.
59        \item The type pointer to (first) element does not.
60        \item C \emph{has} a type that knows the whole picture: array, e.g. @T[10]@.
61        \item This type has all the usual derived forms, which also know the whole picture.
62        A usefully noteworthy example is pointer to array, e.g. @T (*)[10]@.\footnote{
63        The parenthesis are necessary because subscript has higher priority than pointer in C declarations.
64        (Subscript also has higher priority than dereference in C expressions.)}
65\end{itemize}
66
67The following sections introduce the many layers of the C array story, concluding with an \emph{Unfortunate Syntactic Reference}.
68It shows how to define (spell) the types under discussion, along with interactions with orthogonal (but easily confused) language features.
69Alternate spellings are listed within a row.
70The simplest occurrences of types distinguished in the preceding discussion are marked with $\triangleright$.
71The Type column gives the spelling used in a cast or error message (though note Section TODO points out that some types cannot be casted to).
72The Declaration column gives the spelling used in an object declaration, such as variable or aggregate member; parameter declarations (section TODO) follow entirely different rules.
73
74After all, reading a C array type is easy: just read it from the inside out, and know when to look left and when to look right!
75
76
77\CFA-specific spellings (not yet introduced) are also included here for referenceability; these can be skipped on linear reading.
78The \CFA-C column gives the, more fortunate, ``new'' syntax of section TODO, for spelling \emph{exactly the same type}.
79This fortunate syntax does not have different spellings for types vs declarations;
80a declaration is always the type followed by the declared identifier name;
81for the example of letting @x@ be a \emph{pointer to array}, the declaration is spelled:
82\begin{cfa}
83* [10] T x;
84\end{cfa}
85The \CFA-Full column gives the spelling of a different type, introduced in TODO, which has all of my contributed improvements for safety and ergonomics.
86
87Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site.
88For example, a routine returning a \Index{pointer} to an array of integers is defined and used in the following way:
89\begin{cfa}
90int @(*@f@())[@5@]@ {...}; $\C{// definition}$
91 ... @(*@f@())[@3@]@ += 1; $\C{// usage}$
92\end{cfa}
93Essentially, the return type is wrapped around the routine name in successive layers (like an \Index{onion}).
94While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice, even though Dennis Richie believed otherwise:
95\begin{quote}
96In spite of its difficulties, I believe that the C's approach to declarations remains plausible, and am comfortable with it; it is a useful unifying principle.~\cite[p.~12]{Ritchie93}
97\end{quote}
98
99\CFA provides its own type, variable and routine declarations, using a different syntax.
100The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right of the base type.
101In the following example, {\color{red}red} is the base type and {\color{blue}blue} is qualifiers.
102The \CFA declarations move the qualifiers to the left of the base type, \ie move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type.
103\begin{cquote}
104\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
105\multicolumn{1}{c@{\hspace{3em}}}{\textbf{C}}   & \multicolumn{1}{c}{\textbf{\CFA}}     \\
106\begin{cfa}[moredelim={**[is][\color{blue}]{\#}{\#}}]
107@int@ #*# x1 #[5]#;
108@int@ #(*#x2#)[5]#;
109#int (*#f@( int p )@#)[5]#;
110\end{cfa}
111&
112\begin{cfa}[moredelim={**[is][\color{blue}]{\#}{\#}}]
113#[5] *# @int@ x1;
114#* [5]# @int@ x2;
115#[* [5] int]# f@( int p )@;
116\end{cfa}
117\end{tabular}
118\end{cquote}
119
120\VRef[Figure]{bkgd:ar:usr:avp} gives this reference for the discussion so far.
121
122\begin{figure}
123\centering
124\setlength{\tabcolsep}{3pt}
125\begin{tabular}{ll|l|l|l|l}
126        & Description & Type & Declaration & \CFA  & \CFA-thesis \\ \hline
127        $\triangleright$ & val. & @T@ & @T x;@ & @T@ & \\
128        \hline
129        & immutable val. & @const T@ & @T const x;@ & @const T@ & \\
130        & & @T const@ & @T const x;@ & @T const@ & \\
131        \hline \hline
132        $\triangleright$ & ptr.\ to val. & @T *@ & @T * x;@ & @* T@ & \\
133        \hline
134        & immutable ptr. to val. & @T * const@ & @T * const x;@ & @const * T@ & \\
135        \hline
136        & ptr. to immutable val. & @const T *@ & @const T * x;@ & @* const T@ & \\
137        & & @T const *@ & @T const * x;@ & @* T const@ & \\
138        \hline \hline
139        $\triangleright$ & ar.\ of val. & @T[10]@ & @T x[10];@ & @[10] T@ & @array(T, 10)@ \\
140        \hline
141        & ar.\ of immutable val. & @const T[10]@ & @const T x[10];@ & @[10] const T@ & @const array(T, 10)@ \\
142    & & @T const [10]@ & @T const x[10];@ & @[10] T const@ & @array(T, 10) const@ \\
143        \hline
144        & ar.\ of ptr.\ to val. & @T * [10]@ & @T * x[10];@ & @[10] * T@ & @array(T * | * T, 10)@ \\
145        \hline
146        & ar.\ of imm. ptr.\ to val. & @T * const [10]@ & @T * const x[10];@ & @[10] const * T@ & @array(const * T, 10)@ \\
147        \hline
148        & ar.\ of ptr.\ to imm. val. & @const T * [10]@ & @const T * x[10];@ & @[10] * const T@ & @array(* const T, 10)@ \\
149        & & @T const * [10]@ & @T const * x[10];@ & @[10] * T const@ & @array(* T const, 10)@ \\
150        \hline \hline
151        $\triangleright$ & ptr.\ to ar.\ of val. & @T(*)[10]@ & @T (*x)[10];@ & @* [10] T@ & @* array(T, 10)@ \\
152        \hline
153        & imm. ptr.\ to ar.\ of val. & @T(* const)[10]@ & @T (* const x)[10];@ & @const * [10] T@ & @const * array(T, 10)@ \\
154        \hline
155        & ptr.\ to ar.\ of imm. val. & @const T(*)[10]@ & @const T (*x)[10];@ & @* [10] const T@ & @* const array(T, 10)@ \\
156        & & @T const (*) [10]}@ & @T const (*x)[10];@ & @* [10] T const@ & @* array(T, 10) const@ \\
157        \hline
158        & ptr.\ to ar.\ of ptr.\ to val. & @T*(*)[10]@ & @T *(*x)[10];@ & @* [10] * T@ & @* array(T * | * T, 10)@ \\
159        \hline
160\end{tabular}
161\caption{Unfortunate Syntactic Reference for Array vs Pointer.  Includes interaction with constness.}
162\label{bkgd:ar:usr:avp}
163\end{figure}
164
165
166
167
168
169TODO: Address these parked unfortunate syntaxes
170\begin{itemize}
171        \item static
172        \item star as dimension
173        \item under pointer decay:                              int p1[const 3]  being  int const *p1
174\end{itemize}
175
176
177\subsection{Arrays decay and pointers diffract}
178
179The last section established the difference between these four types:
180\lstinput{3-6}{bkgd-carray-decay.c}
181But the expression used for obtaining the pointer to the first element is pedantic.
182The root of all C programmer experience with arrays is the shortcut
183\lstinput{8-8}{bkgd-carray-decay.c}
184which reproduces @pa0@, in type and value:
185\lstinput{9-9}{bkgd-carray-decay.c}
186The validity of this initialization is unsettling, in the context of the facts established in the last section.
187Notably, it initializes name @pa0x@ from expression @ar@, when they are not of the same type:
188\lstinput{10-10}{bkgd-carray-decay.c}
189
190So, C provides an implicit conversion from @float[10]@ to @float*@, as described in ARM-6.3.2.1.3:
191\begin{quote}
192Except when it is the operand of the @sizeof@ operator, or the unary @&@ operator, or is a
193string literal used to initialize an array
194an expression that has type ``array of type'' is
195converted to an expression with type ``pointer to type'' that points to the initial element of
196the array object
197\end{quote}
198
199This phenomenon is the famous ``pointer decay,'' which is a decay of an array-typed expression into a pointer-typed one.
200
201It is worthy to note that the list of exception cases does not feature the occurrence of @ar@ in @ar[i]@.
202Thus, subscripting happens on pointers, not arrays.
203
204Subscripting proceeds first with pointer decay, if needed.  Next, ARM-6.5.2.1.2 explains that @ar[i]@ is treated as if it were @(*((a)+(i)))@.
205ARM-6.5.6.8 explains that the addition, of a pointer with an integer type,  is defined only when the pointer refers to an element that is in an array, with a meaning of ``@i@ elements away from,'' which is valid if @ar@ is big enough and @i@ is small enough.
206Finally, ARM-6.5.3.2.4 explains that the @*@ operator's result is the referenced element.
207
208Taken together, these rules also happen to illustrate that @ar[i]@ and @i[a]@ mean the same thing.
209
210Subscripting a pointer when the target is standard-inappropriate is still practically well-defined.
211While the standard affords a C compiler freedom about the meaning of an out-of-bound access,
212or of subscripting a pointer that does not refer to an array element at all,
213the fact that C is famously both generally high-performance, and specifically not bound-checked,
214leads to an expectation that the runtime handling is uniform across legal and illegal accesses.
215Moreover, consider the common pattern of subscripting on a @malloc@ result:
216\begin{cfa}
217float * fs = malloc( 10 * sizeof(float) );
218fs[5] = 3.14;
219\end{cfa}
220The @malloc@ behaviour is specified as returning a pointer to ``space for an object whose size is'' as requested (ARM-7.22.3.4.2).
221But program says \emph{nothing} more about this pointer value, that might cause its referent to \emph{be} an array, before doing the subscript.
222
223Under this assumption, a pointer being subscripted (or added to, then dereferenced)
224by any value (positive, zero, or negative), gives a view of the program's entire address space,
225centred around the @p@ address, divided into adjacent @sizeof(*p)@ chunks,
226each potentially (re)interpreted as @typeof(*p)@.
227
228I call this phenomenon ``array diffraction,''  which is a diffraction of a single-element pointer
229into the assumption that its target is in the middle of an array whose size is unlimited in both directions.
230
231No pointer is exempt from array diffraction.
232
233No array shows its elements without pointer decay.
234
235A further pointer--array confusion, closely related to decay, occurs in parameter declarations.
236ARM-6.7.6.3.7 explains that when an array type is written for a parameter,
237the parameter's type becomes a type that I summarize as being the array-decayed type.
238The respective handling of the following two parameter spellings shows that the array-spelled one is really, like the other, a pointer.
239\lstinput{12-16}{bkgd-carray-decay.c}
240As the @sizeof(x)@ meaning changed, compared with when run on a similarly-spelled local variable declaration,
241GCC also gives this code the warning: ```sizeof' on array function parameter `x' will return size of `float *'.''
242
243The caller of such a function is left with the reality that a pointer parameter is a pointer, no matter how it's spelled:
244\lstinput{18-21}{bkgd-carray-decay.c}
245This fragment gives no warnings.
246
247The shortened parameter syntax @T x[]@ is a further way to spell ``pointer.''
248Note the opposite meaning of this spelling now, compared with its use in local variable declarations.
249This point of confusion is illustrated in:
250\lstinput{23-30}{bkgd-carray-decay.c}
251The basic two meanings, with a syntactic difference helping to distinguish,
252are illustrated in the declarations of @ca@ vs.\ @cp@,
253whose subsequent @edit@ calls behave differently.
254The syntax-caused confusion is in the comparison of the first and last lines,
255both of which use a literal to initialize an object declared with spelling @T x[]@.
256But these initialized declarations get opposite meanings,
257depending on whether the object is a local variable or a parameter.
258
259
260In summary, when a function is written with an array-typed parameter,
261\begin{itemize}
262        \item an appearance of passing an array by value is always an incorrect understanding
263        \item a dimension value, if any is present, is ignored
264        \item pointer decay is forced at the call site and the callee sees the parameter having the decayed type
265\end{itemize}
266
267Pointer decay does not affect pointer-to-array types, because these are already pointers, not arrays.
268As a result, a function with a pointer-to-array parameter sees the parameter exactly as the caller does:
269\lstinput{32-42}{bkgd-carray-decay.c}
270
271\VRef[Figure]{bkgd:ar:usr:decay-parm} gives the reference for the decay phenomenon seen in parameter declarations.
272
273\begin{figure}
274\centering
275\begin{tabular}{llllll}
276        & Description & Type & Param. Decl & \CFA-C  \\ \hline
277        $\triangleright$ & ptr.\ to val.
278            & @T *@
279            & \pbox{20cm}{ \vspace{2pt} \lstinline{T * x,} \\ \lstinline{T x[10],} \\ \lstinline{T x[],}   }\vspace{2pt}
280            & \pbox{20cm}{ \vspace{2pt} \lstinline{[ * T ]} \\ \lstinline{[ [10] T ]} \\ \lstinline{[ [] T  ]}   }
281            \\ \hline
282        & \pbox{20cm}{ \vspace{2pt} ptr.\ to val.\\ \footnotesize{no writing the ptr.\ in \lstinline{x}}   }\vspace{2pt}
283            & @T * const@
284            & \pbox{20cm}{ \vspace{2pt} \lstinline{T * const x,} \\ \lstinline{T x[const 10],} \\ \lstinline{T x[const],}   }\vspace{2pt}
285            & \pbox{20cm}{ \vspace{2pt} \lstinline{[ const * T ]} \\ \lstinline{[ [const 10] T ]} \\ \lstinline{[ [const] T  ]}   }
286            \\ \hline
287        & \pbox{20cm}{ \vspace{2pt} ptr.\ to val.\\ \footnotesize{no writing the val.\ in \lstinline{*x}}   }\vspace{2pt}
288            & \pbox{20cm}{ \vspace{2pt} \lstinline{const T *} \\ \lstinline{T const *}   }
289            & \pbox{20cm}{ \vspace{2pt} \lstinline{const T * x,} \\ \lstinline{T const * x,} \\ \lstinline{const T x[10],} \\ \lstinline{T const x[10],} \\ \lstinline{const T x[],} \\ \lstinline{T const x[],}   }\vspace{2pt}
290            & \pbox{20cm}{ \vspace{2pt} \lstinline{[* const T]} \\ \lstinline{[ [10] const T ]} \\ \lstinline{[ [] const T  ]}   }
291            \\ \hline \hline
292        $\triangleright$ & ptr.\ to ar.\ of val.
293            & @T(*)[10]@
294            & \pbox{20cm}{ \vspace{2pt} \lstinline{T (*x)[10],} \\ \lstinline{T x[3][10],} \\ \lstinline{T x[][10],}   }\vspace{2pt}
295            & \pbox{20cm}{ \vspace{2pt} \lstinline{[* [10] T]} \\ \lstinline{[ [3] [10] T ]} \\ \lstinline{[ [] [10] T  ]}   }
296            \\ \hline
297        & ptr.\ to ptr.\ to val.
298            & @T **@
299            & \pbox{20cm}{ \vspace{2pt} \lstinline{T ** x,} \\ \lstinline{T *x[10],} \\ \lstinline{T *x[],}   }\vspace{2pt}
300            & \pbox{20cm}{ \vspace{2pt} \lstinline{[ * * T ]} \\ \lstinline{[ [10] * T ]} \\ \lstinline{[ [] * T  ]}   }
301            \\ \hline
302        & \pbox{20cm}{ \vspace{2pt} ptr.\ to ptr.\ to val.\\ \footnotesize{no writing the val.\ in \lstinline{**argv}}   }\vspace{2pt}
303            & @const char **@
304            & \pbox{20cm}{ \vspace{2pt} \lstinline{const char *argv[],} \\ \footnotesize{(others elided)}   }\vspace{2pt}
305            & \pbox{20cm}{ \vspace{2pt} \lstinline{[ [] * const char ]} \\ \footnotesize{(others elided)}   }
306            \\ \hline
307\end{tabular}
308\caption{Unfortunate Syntactic Reference for Decay during Parameter-Passing.  Includes interaction with constness, where ``no writing'' refers to a restriction on the callee's ability.}
309\label{bkgd:ar:usr:decay-parm}
310\end{figure}
311
312
313\subsection{Lengths may vary, checking does not}
314
315When the desired number of elements is unknown at compile time,
316a variable-length array is a solution:
317\begin{cfa}
318int main( int argc, const char *argv[] ) {
319        assert( argc == 2 );
320        size_t n = atol( argv[1] );
321        assert( 0 < n && n < 1000 );
322
323        float ar[n];
324        float b[10];
325
326        // ... discussion continues here
327}
328\end{cfa}
329This arrangement allocates @n@ elements on the @main@ stack frame for @ar@, just as it puts 10 elements on the @main@ stack frame for @b@.
330The variable-sized allocation of @ar@ is provided by @alloca@.
331
332In a situation where the array sizes are not known to be small enough for stack allocation to be sensible, corresponding heap allocations are achievable as:
333\begin{cfa}
334float *ax1 = malloc( sizeof( float[n] ) );
335float *ax2 = malloc( n * sizeof( float ) );
336float *bx1 = malloc( sizeof( float[1000000] ) );
337float *bx2 = malloc( 1000000 * sizeof( float ) );
338\end{cfa}
339
340
341VLA
342
343Parameter dependency
344
345Checking is best-effort / unsound
346
347Limited special handling to get the dimension value checked (static)
348
349
350
351\subsection{C has full-service, dynamically sized, multidimensional arrays (and \CC does not)}
352
353In C and \CC, ``multidimensional array'' means ``array of arrays.''  Other meanings are discussed in TODO.
354
355Just as an array's element type can be @float@, so can it be @float[10]@.
356
357While any of @float*@, @float[10]@ and @float(*)[10]@ are easy to tell apart from @float@, telling them apart from each other may need occasional reference back to TODO intro section.
358The sentence derived by wrapping each type in @-[3]@ follows.
359
360While any of @float*[3]@, @float[3][10]@ and @float(*)[3][10]@ are easy to tell apart from @float[3]@,
361telling them apart from each other is what it takes to know what ``array of arrays'' really means.
362
363Pointer decay affects the outermost array only
364
365TODO: unfortunate syntactic reference with these cases:
366
367\begin{itemize}
368        \item ar. of ar. of val (be sure about ordering of dimensions when the declaration is dropped)
369        \item ptr. to ar. of ar. of val
370\end{itemize}
371
372
373\subsection{Arrays are (but) almost values}
374
375Has size; can point to
376
377Can't cast to
378
379Can't pass as value
380
381Can initialize
382
383Can wrap in aggregate
384
385Can't assign
386
387
388\subsection{Returning an array is (but) almost possible}
389
390
391\subsection{The pointer-to-array type has been noticed before}
392
393\subsection{Multi-Dimensional}
394
395As in the last section, we inspect the declaration ...
396\lstinput{16-18}{bkgd-carray-mdim.c}
397The significant axis of deriving expressions from @ar@ is now ``itself,'' ``first element'' or ``first grand-element (meaning, first element of first element).''
398\lstinput{20-44}{bkgd-carray-mdim.c}
399
400
401\section{Linked List}
402
403
404\section{String}
Note: See TracBrowser for help on using the repository browser.