source: doc/theses/mike_brooks_MMath/array.tex @ 76425bc

Last change on this file since 76425bc was 82e5670, checked in by Peter A. Buhr <pabuhr@…>, 8 months ago

add material from background

  • Property mode set to 100644
File size: 36.2 KB
RevLine 
[bbf6a180]1\chapter{Array}
2
[40ab446]3\section{Introduction}
4
5This chapter describes my contribution of language and library features that provide a length-checked array type, as in:
6
7\begin{lstlisting}
[266732e]8array(float, 99) x;    // x contains 99 floats
[40ab446]9
[266732e]10void f( array(float, 42) & a ) {}
11f(x);                  // statically rejected: types are different
[40ab446]12
[266732e]13forall( T, [N] )
14void g( array(T, N) & a, int i ) {
15        T elem = a[i];     // dynamically checked: requires 0 <= i < N
16}
17g(x, 0);               // T is float, N is 99, succeeds
18g(x, 1000);            // T is float, N is 99, dynamic check fails
[40ab446]19\end{lstlisting}
20
21This example first declares @x@ a variable, whose type is an instantiation of the generic type named @array@, with arguments @float@ and @99@.
22Next, it declares @f@ as a function that expects a length-42 array; the type system rejects the call's attempt to pass @x@ to @f@, because the lengths do not match.
23Next, the @forall@ annotation on function @g@ introduces @T@ as a familiar type parameter and @N@ as a \emph{dimension} parameter, a new feature that represents a count of elements, as managed by the type system.
24Because @g@ accepts any length of array; the type system accepts the calls' passing @x@ to @g@, inferring that this length is 99.
25Just as the caller's code does not need to explain that @T@ is @float@, the safe capture and communication of the value @99@ occurs without programmer involvement.
26In the case of the second call (which passes the value 1000 for @i@), within the body of @g@, the attempt to subscript @a@ by @i@ fails with a runtime error, since $@i@ \nless @N@$.
27
28The type @array@, as seen above, comes from my additions to the \CFA standard library.
29It is very similar to the built-in array type, which \CFA inherits from C.
30Its runtime characteristics are often identical, and some features are available in both.
31
32\begin{lstlisting}
[266732e]33forall( [N] )
34void declDemo() {
35        float a1[N];         // built-in type ("C array")
36        array(float, N) a2;  // type from library
37}
[40ab446]38\end{lstlisting}
39
40If a caller instantiates @N@ with 42, then both locally-declared array variables, @a1@ and @a2@, become arrays of 42 elements, each element being a @float@.
41The two variables have identical size and layout; they both encapsulate 42-float stack allocations, no heap allocations, and no further "bookkeeping" allocations/header.
42Having the @array@ library type (that of @a2@) is a tactical measure, an early implementation that offers full feature support.
43A future goal (TODO xref) is to port all of its features into the built-in array type (that of @a1@); then, the library type could be removed, and \CFA would have only one array type.
44In present state, the built-in array has partial support for the new features.
45The fully-featured library type is used exclusively in introductory examples; feature support and C compatibility are revisited in sec TODO.
46
47Offering the @array@ type, as a distinct alternative from the the C array, is consistent with \CFA's extension philosophy (TODO xref background) to date.
48A few compatibility-breaking changes to the behaviour of the C array were also made, both as an implementation convenience, and as justified fixes to C's lax treatment.
49
50The @array@ type is an opportunity to start from a clean slate and show a cohesive selection of features.
51A clean slate was an important starting point because it meant not having to deal with every inherited complexity introduced in TODO xref background-array.
52
53
54My contributions are
55\begin{itemize}
[266732e]56\item a type system enhancement that lets polymorphic functions and generic types be parameterized by a numeric value: @forall( [N] )@
57\item TODO: general parking...
58\item identify specific abilities brought by @array@
59\item Where there is a gap concerning this feature's readiness for prime-time, identification of specific workable improvements that are likely to close the gap
[40ab446]60\end{itemize}
61
62
63\section{Definitions and design considerations}
64
65
[266732e]66\subsection{Dependent typing}
[40ab446]67
[dab9fb93]68
[bbf6a180]69\section{Features Added}
70
[5a9bc1e]71The present work adds a type @array@ to the \CFA standard library~\cite{Cforall}.
[bbf6a180]72
[266732e]73This array's length is statically managed and dynamically valued.
74This static management achieves argument safety and suggests a path to subscript safety as future work (TODO: cross reference).
[bbf6a180]75
[dab9fb93]76This section presents motivating examples of the new array type's usage and follows up with definitions of the notations that appear.
[bbf6a180]77
[266732e]78The core of the new array management is tracking all array lengths in the type system.
79Dynamically valued lengths are represented using type variables.
80The stratification of type variables preceding object declarations makes a length referenceable everywhere that it is needed.
81For example, a declaration can share one length, @N@, among a pair of parameters and the return.
[b64d0f4]82\lstinput{10-17}{hello-array.cfa}
[dab9fb93]83Here, the function @f@ does a pointwise comparison, checking if each pair of numbers is within half a percent of each other, returning the answers in a newly allocated @bool@ array.
[bbf6a180]84
[266732e]85The array type uses the parameterized length information in its @sizeof@ determination, illustrated in the example's call to @alloc@.
86That call requests an allocation of type @array(bool, N)@, which the type system deduces from the left-hand side of the initialization, into the return type of the @alloc@ call.
87Preexisting \CFA behaviour is leveraged here, both in the return-type-only polymorphism, and the @sized(T)@-aware standard-library @alloc@ routine.
88The new @array@ type plugs into this behaviour by implementing the @sized@/@sizeof@ assertion to have the intuitive meaning.
89As a result, this design avoids an opportunity for programmer error by making the size/length communication to a called routine implicit, compared with C's @calloc@ (or the low-level \CFA analog @aalloc@), which take an explicit length parameter not managed by the type system.
[bbf6a180]90
[dab9fb93]91\VRef[Figure]{f:fHarness} shows the harness to use the @f@ function illustrating how dynamic values are fed into the system.
[266732e]92Here, the @a@ array is loaded with decreasing values, and the @b@ array with amounts off by a constant, giving relative differences within tolerance at first and out of tolerance later.
93The program main is run with two different inputs of sequence length.
[bbf6a180]94
[dab9fb93]95\begin{figure}
[b64d0f4]96\lstinput{30-49}{hello-array.cfa}
[dab9fb93]97\caption{\lstinline{f} Harness}
98\label{f:fHarness}
99\end{figure}
[bbf6a180]100
[266732e]101The loops in the program main follow the more familiar pattern of using the ordinary variable @n@ to convey the length.
102The type system implicitly captures this value at the call site (@main@ calling @f@) and makes it available within the callee (@f@'s loop bound).
[bbf6a180]103
[dab9fb93]104The two parts of the example show @n@ adapting a variable into a type-system managed length (at @main@'s declarations of @a@, @b@, and @result@), @N@ adapting in the opposite direction (at @f@'s loop bound), and a pass-thru use of a managed length (at @f@'s declaration of @ret@).
[bbf6a180]105
[266732e]106The @forall( ...[N] )@ participates in the user-relevant declaration of the name @N@, which becomes usable in parameter/return declarations and in the function @b@.
107The present form is chosen to parallel the existing @forall@ forms:
[dab9fb93]108\begin{cfa}
109forall( @[N]@ ) ... // array kind
110forall( & T  ) ...  // reference kind (dtype)
111forall( T  ) ...    // value kind (otype)
112\end{cfa}
[bbf6a180]113
[dab9fb93]114The notation @array(thing, N)@ is a single-dimensional case, giving a generic type instance.
[bbf6a180]115In summary:
[dab9fb93]116\begin{itemize}
117\item
118@[N]@ -- within a forall, declares the type variable @N@ to be a managed length
119\item
120$e$ -- a type representing the value of $e$ as a managed length, where $e$ is a @size_t@-typed expression
121\item
122N -- an expression of type @size_t@, whose value is the managed length @N@
123\item
124@array( thing, N0, N1, ... )@ -- a type wrapping $\prod_i N_i$ adjacent occurrences of @thing@ objects
125\end{itemize}
[266732e]126Unsigned integers have a special status in this type system.
127Unlike how C++ allows
128\begin{lstlisting}[language=c++]
129template< size_t N, char * msg, typename T >... // declarations
130\end{lstlisting}
131\CFA does not accommodate values of any user-provided type.
132TODO: discuss connection with dependent types.
133An example of a type error demonstrates argument safety.
134The running example has @f@ expecting two arrays of the same length.
135A compile-time error occurs when attempting to call @f@ with arrays whose lengths may differ.
136\begin{cfa}
137forall( [M], [N] )
138void bad( array(float, M) &a, array(float, N) &b ) {
139        f( a, a ); // ok
140        f( b, b ); // ok
141        f( a, b ); // error
142}
143\end{cfa}
[b64d0f4]144%\lstinput{60-65}{hello-array.cfa}
[dab9fb93]145As is common practice in C, the programmer is free to cast, to assert knowledge not shared with the type system.
[266732e]146\begin{cfa}
147forall( [M], [N] )
148void bad_fixed( array(float, M) & a, array(float, N) & b ) {
149        if ( M == N ) {
150            f( a, (array(float, M) &)b ); // cast b to matching type
151        }
152}
153\end{cfa}
[b64d0f4]154%\lstinput{70-75}{hello-array.cfa}
[dab9fb93]155
156Argument safety and the associated implicit communication of array length work with \CFA's generic types too.
157\CFA allows aggregate types to be generalized with multiple type parameters, including parameterized element type, so can it be defined over a parameterized length.
158Doing so gives a refinement of C's ``flexible array member'' pattern, that allows nesting structures with array members anywhere within other structures.
[b64d0f4]159\lstinput{10-16}{hello-accordion.cfa}
[266732e]160This structure's layout has the starting offset of @cost_contribs@ varying in @Nclients@, and the offset of @total_cost@ varying in both generic parameters.
161For a function that operates on a @request@ structure, the type system handles this variation transparently.
[b64d0f4]162\lstinput{40-47}{hello-accordion.cfa}
[dab9fb93]163In the example, different runs of the program result in different offset values being used.
[b64d0f4]164\lstinput{60-76}{hello-accordion.cfa}
[266732e]165The output values show that @summarize@ and its caller agree on both the offsets (where the callee starts reading @cost_contribs@ and where the callee writes @total_cost@).
166Yet the call site still says just, ``pass the request.''
[bbf6a180]167
168
169\section{Multidimensional implementation}
170\label{toc:mdimpl}
171
172TODO: introduce multidimensional array feature and approaches
173
[266732e]174The new \CFA standard library @array@ datatype supports multidimensional uses more richly than the C array.
175The new array's multidimensional interface and implementation, follows an array-of-arrays setup, meaning, like C's @float[n][m]@ type, one contiguous object, with coarsely-strided dimensions directly wrapping finely-strided dimensions.
176This setup is in contrast with the pattern of array of pointers to other allocations representing a sub-array.
177Beyond what C's type offers, the new array brings direct support for working with a noncontiguous array slice, allowing a program to work with dimension subscripts given in a non-physical order.
178C and C++ require a programmer with such a need to manage pointer/offset arithmetic manually.
[bbf6a180]179
[dab9fb93]180Examples are shown using a $5 \times 7$ float array, @a@, loaded with increments of $0.1$ when stepping across the length-7 finely-strided dimension shown on columns, and with increments of $1.0$ when stepping across the length-5 coarsely-strided dimension shown on rows.
[b64d0f4]181%\lstinput{120-126}{hello-md.cfa}
[bbf6a180]182The memory layout of @a@ has strictly increasing numbers along its 35 contiguous positions.
183
[266732e]184A trivial form of slicing extracts a contiguous inner array, within an array-of-arrays.
185Like with the C array, a lesser-dimensional array reference can be bound to the result of subscripting a greater-dimensional array, by a prefix of its dimensions.
186This action first subscripts away the most coarsely strided dimensions, leaving a result that expects to be be subscripted by the more finely strided dimensions.
[b64d0f4]187\lstinput{60-66}{hello-md.cfa}
188\lstinput[aboveskip=0pt]{140-140}{hello-md.cfa}
[bbf6a180]189
[266732e]190This function declaration is asserting too much knowledge about its parameter @c@, for it to be usable for printing either a row slice or a column slice.
191Specifically, declaring the parameter @c@ with type @array@ means that @c@ is contiguous.
192However, the function does not use this fact.
193For the function to do its job, @c@ need only be of a container type that offers a subscript operator (of type @ptrdiff_t@ $\rightarrow$ @float@), with managed length @N@.
194The new-array library provides the trait @ix@, so-defined.
195With it, the original declaration can be generalized, while still implemented with the same body, to the latter declaration:
[b64d0f4]196\lstinput{40-44}{hello-md.cfa}
197\lstinput[aboveskip=0pt]{145-145}{hello-md.cfa}
[bbf6a180]198
[266732e]199Nontrivial slicing, in this example, means passing a noncontiguous slice to @print1d@.
200The new-array library provides a ``subscript by all'' operation for this purpose.
201In a multi-dimensional subscript operation, any dimension given as @all@ is left ``not yet subscripted by a value,'' implementing the @ix@ trait, waiting for such a value.
[b64d0f4]202\lstinput{150-151}{hello-md.cfa}
[bbf6a180]203
[266732e]204The example has shown that @a[2]@ and @a[[2, all]]@ both refer to the same, ``2.*'' slice.
205Indeed, the various @print1d@ calls under discussion access the entry with value 2.3 as @a[2][3]@, @a[[2,all]][3]@, and @a[[all,3]][2]@.
206This design preserves (and extends) C array semantics by defining @a[[i,j]]@ to be @a[i][j]@ for numeric subscripts, but also for ``subscripting by all''.
207That is:
[bbf6a180]208
209\begin{tabular}{cccccl}
[266732e]210@a[[2,all]][3]@  &  $=$  &  @a[2][all][3]@  & $=$  &  @a[2][3]@  & (here, @all@ is redundant)  \\
211@a[[all,3]][2]@  &  $=$  &  @a[all][3][2]@  & $=$  &  @a[2][3]@  & (here, @all@ is effective)
[bbf6a180]212\end{tabular}
213
214Narrating progress through each of the @-[-][-][-]@ expressions gives, firstly, a definition of @-[all]@, and secondly, a generalization of C's @-[i]@.
215
216\noindent Where @all@ is redundant:
217
218\begin{tabular}{ll}
[266732e]219@a@  & 2-dimensional, want subscripts for coarse then fine \\
220@a[2]@  & 1-dimensional, want subscript for fine; lock coarse = 2 \\
221@a[2][all]@  & 1-dimensional, want subscript for fine \\
222@a[2][all][3]@  & 0-dimensional; lock fine = 3
[bbf6a180]223\end{tabular}
224
225\noindent Where @all@ is effective:
226
227\begin{tabular}{ll}
[266732e]228@a@  & 2-dimensional, want subscripts for coarse then fine \\
229@a[all]@  & 2-dimensional, want subscripts for fine then coarse \\
230@a[all][3]@  & 1-dimensional, want subscript for coarse; lock fine = 3 \\
231@a[all][3][2]@  & 0-dimensional; lock coarse = 2
[bbf6a180]232\end{tabular}
233
[266732e]234The semantics of @-[all]@ is to dequeue from the front of the ``want subscripts'' list and re-enqueue at its back.
235The semantics of @-[i]@ is to dequeue from the front of the ``want subscripts'' list and lock its value to be @i@.
[bbf6a180]236
[266732e]237Contiguous arrays, and slices of them, are all realized by the same underlying parameterized type.
238It includes stride information in its metatdata.
239The @-[all]@ operation is a conversion from a reference to one instantiation, to a reference to another instantiation.
240The running example's @all@-effective step, stated more concretely, is:
[bbf6a180]241
242\begin{tabular}{ll}
[266732e]243@a@       & : 5 of ( 7 of float each spaced 1 float apart ) each spaced 7 floats apart \\
244@a[all]@  & : 7 of ( 5 of float each spaced 7 floats apart ) each spaced 1 float apart
[bbf6a180]245\end{tabular}
246
247\begin{figure}
[266732e]248\includegraphics{measuring-like-layout}
249\caption{Visualization of subscripting by value and by \lstinline[language=CFA,basicstyle=\ttfamily]{all}, for \lstinline[language=CFA,basicstyle=\ttfamily]{a} of type \lstinline[language=CFA,basicstyle=\ttfamily]{array( float, 5, 7 )}.
250The horizontal dimension represents memory addresses while vertical layout is conceptual.}
251\label{fig:subscr-all}
[bbf6a180]252\end{figure}
253
[266732e]254\noindent While the latter description implies overlapping elements, Figure \ref{fig:subscr-all} shows that the overlaps only occur with unused spaces between elements.
255Its depictions of @a[all][...]@ show the navigation of a memory layout with nontrivial strides, that is, with ``spaced \_ floats apart'' values that are greater or smaller than the true count of valid indices times the size of a logically indexed element.
256Reading from the bottom up, the expression @a[all][3][2]@ shows a float, that is masquerading as a @float[7]@, for the purpose of being arranged among its peers; five such occurrences form @a[all][3]@.
257The tail of flatter boxes extending to the right of a proper element represents this stretching.
258At the next level of containment, the structure @a[all][3]@ masquerades as a @float[1]@, for the purpose of being arranged among its peers; seven such occurrences form @a[all]@.
259The vertical staircase arrangement represents this compression, and resulting overlapping.
[bbf6a180]260
[266732e]261The new-array library defines types and operations that ensure proper elements are accessed soundly in spite of the overlapping.
262The private @arpk@ structure (array with explicit packing) is generic over these two types (and more): the contained element, what it is masquerading as.
263This structure's public interface is the @array(...)@ construction macro and the two subscript operators.
264Construction by @array@ initializes the masquerading-as type information to be equal to the contained-element information.
265Subscripting by @all@ rearranges the order of masquerading-as types to achieve, in general, nontrivial striding.
266Subscripting by a number consumes the masquerading-as size of the contained element type, does normal array stepping according to that size, and returns there element found there, in unmasked form.
[bbf6a180]267
268The @arpk@ structure and its @-[i]@ operator are thus defined as:
269\begin{lstlisting}
270forall( ztype(N),               // length of current dimension
[266732e]271        dtype(S) | sized(S),    // masquerading-as
272        dtype E_im,             // immediate element, often another array
273        dtype E_base            // base element, e.g. float, never array
274 ) {
275struct arpk {
276        S strides[N];           // so that sizeof(this) is N of S
277};
278
279// expose E_im, stride by S
280E_im & ?[?]( arpk(N, S, E_im, E_base) & a, ptrdiff_t i ) {
281        return (E_im &) a.strides[i];
282}
[bbf6a180]283}
284\end{lstlisting}
285
[266732e]286An instantiation of the @arpk@ generic is given by the @array(E_base, N0, N1, ...)@ expansion, which is @arpk( N0, Rec, Rec, E_base )@, where @Rec@ is @array(E_base, N1, ...)@.
287In the base case, @array(E_base)@ is just @E_base@.
288Because this construction uses the same value for the generic parameters @S@ and @E_im@, the resulting layout has trivial strides.
[bbf6a180]289
[266732e]290Subscripting by @all@, to operate on nontrivial strides, is a dequeue-enqueue operation on the @E_im@ chain, which carries @S@ instantiations, intact, to new positions.
291Expressed as an operation on types, this rotation is:
[bbf6a180]292\begin{eqnarray*}
293suball( arpk(N, S, E_i, E_b) ) & = & enq( N, S, E_i, E_b ) \\
294enq( N, S, E_b, E_b ) & = & arpk( N, S, E_b, E_b ) \\
295enq( N, S, arpk(N', S', E_i', E_b), E_b ) & = & arpk( N', S', enq(N, S, E_i', E_b), E_b )
296\end{eqnarray*}
[8d76f2b]297
298
299\section{Bound checks, added and removed}
300
[266732e]301\CFA array subscripting is protected with runtime bound checks.
302Having dependent typing causes the optimizer to remove more of these bound checks than it would without them.
303This section provides a demonstration of the effect.
[8d76f2b]304
[266732e]305The experiment compares the \CFA array system with the padded-room system [TODO:xref] most typically exemplified by Java arrays, but also reflected in the C++ pattern where restricted vector usage models a checked array.
306The essential feature of this padded-room system is the one-to-one correspondence between array instances and the symbolic bounds on which dynamic checks are based.
307The experiment compares with the C++ version to keep access to generated assembly code simple.
[8d76f2b]308
[266732e]309As a control case, a simple loop (with no reused dimension sizes) is seen to get the same optimization treatment in both the \CFA and C++ versions.
310When the programmer treats the array's bound correctly (making the subscript ``obviously fine''), no dynamic bound check is observed in the program's optimized assembly code.
311But when the bounds are adjusted, such that the subscript is possibly invalid, the bound check appears in the optimized assembly, ready to catch an occurrence the mistake.
[8d76f2b]312
[dab9fb93]313TODO: paste source and assembly codes
[8d76f2b]314
[266732e]315Incorporating reuse among dimension sizes is seen to give \CFA an advantage at being optimized.
316The case is naive matrix multiplication over a row-major encoding.
[8d76f2b]317
318TODO: paste source codes
319
320
321
322
323
324\section{Comparison with other arrays}
325
[266732e]326\CFA's array is the first lightweight application of dependently-typed bound tracking to an extension of C.
327Other extensions of C that apply dependently-typed bound tracking are heavyweight, in that the bound tracking is part of a linearly typed ownership system that further helps guarantee statically the validity of every pointer deference.
328These systems, therefore, ask the programmer to convince the type checker that every pointer dereference is valid.
329\CFA imposes the lighter-weight obligation, with the more limited guarantee, that initially-declared bounds are respected thereafter.
[8d76f2b]330
[266732e]331\CFA's array is also the first extension of C to use its tracked bounds to generate the pointer arithmetic implied by advanced allocation patterns.
332Other bound-tracked extensions of C either forbid certain C patterns entirely, or address the problem of \emph{verifying} that the user's provided pointer arithmetic is self-consistent.
333The \CFA array, applied to accordion structures [TOD: cross-reference] \emph{implies} the necessary pointer arithmetic, generated automatically, and not appearing at all in a user's program.
[8d76f2b]334
[6bf35d1]335\subsection{Safety in a padded room}
[8d76f2b]336
[266732e]337Java's array [TODO:cite] is a straightforward example of assuring safety against undefined behaviour, at a cost of expressiveness for more applied properties.
338Consider the array parameter declarations in:
[8d76f2b]339
340\begin{tabular}{rl}
[266732e]341C      &  @void f( size_t n, size_t m, float a[n][m] );@ \\
342Java   &  @void f( float[][] a );@
[8d76f2b]343\end{tabular}
344
[266732e]345Java's safety against undefined behaviour assures the callee that, if @a@ is non-null, then @a.length@ is a valid access (say, evaluating to the number $\ell$) and if @i@ is in $[0, \ell)$ then @a[i]@ is a valid access.
346If a value of @i@ outside this range is used, a runtime error is guaranteed.
347In these respects, C offers no guarantees at all.
348Notably, the suggestion that @n@ is the intended size of the first dimension of @a@ is documentation only.
349Indeed, many might prefer the technically equivalent declarations @float a[][m]@ or @float (*a)[m]@ as emphasizing the ``no guarantees'' nature of an infrequently used language feature, over using the opportunity to explain a programmer intention.
350Moreover, even if @a[0][0]@ is valid for the purpose intended, C's basic infamous feature is the possibility of an @i@, such that @a[i][0]@ is not valid for the same purpose, and yet, its evaluation does not produce an error.
[8d76f2b]351
352Java's lack of expressiveness for more applied properties means these outcomes are possible:
353\begin{itemize}
[266732e]354\item @a[0][17]@ and @a[2][17]@ are valid accesses, yet @a[1][17]@ is a runtime error, because @a[1]@ is a null pointer
355\item the same observation, now because @a[1]@ refers to an array of length 5
356\item execution times vary, because the @float@ values within @a@ are sometimes stored nearly contiguously, and other times, not at all
[8d76f2b]357\end{itemize}
358C's array has none of these limitations, nor do any of the ``array language'' comparators discussed in this section.
359
[266732e]360This Java level of safety and expressiveness is also exemplified in the C family, with the commonly given advice [TODO:cite example], for C++ programmers to use @std::vector@ in place of the C++ language's array, which is essentially the C array.
361The advice is that, while a vector is also more powerful (and quirky) than an array, its capabilities include options to preallocate with an upfront size, to use an available bound-checked accessor (@a.at(i)@ in place of @a[i]@), to avoid using @push_back@, and to use a vector of vectors.
362Used with these restrictions, out-of-bound accesses are stopped, and in-bound accesses never exercise the vector's ability to grow, which is to say, they never make the program slow to reallocate and copy, and they never invalidate the program's other references to the contained values.
363Allowing this scheme the same referential integrity assumption that \CFA enjoys [TODO:xref], this scheme matches Java's safety and expressiveness exactly.
364[TODO: decide about going deeper; some of the Java expressiveness concerns have mitigations, up to even more tradeoffs.]
[8d76f2b]365
366\subsection{Levels of dependently typed arrays}
367
368The \CFA array and the field of ``array language'' comparators all leverage dependent types to improve on the expressiveness over C and Java, accommodating examples such as:
369\begin{itemize}
[266732e]370\item a \emph{zip}-style operation that consumes two arrays of equal length
371\item a \emph{map}-style operation whose produced length matches the consumed length
372\item a formulation of matrix multiplication, where the two operands must agree on a middle dimension, and where the result dimensions match the operands' outer dimensions
[8d76f2b]373\end{itemize}
[266732e]374Across this field, this expressiveness is not just an available place to document such assumption, but these requirements are strongly guaranteed by default, with varying levels of statically/dynamically checked and ability to opt out.
375Along the way, the \CFA array also closes the safety gap (with respect to bounds) that Java has over C.
[8d76f2b]376
[266732e]377Dependent type systems, considered for the purpose of bound-tracking, can be full-strength or restricted.
378In a full-strength dependent type system, a type can encode an arbitrarily complex predicate, with bound-tracking being an easy example.
379The tradeoff of this expressiveness is complexity in the checker, even typically, a potential for its nontermination.
380In a restricted dependent type system (purposed for bound tracking), the goal is to check helpful properties, while keeping the checker well-behaved; the other restricted checkers surveyed here, including \CFA's, always terminate.
381[TODO: clarify how even Idris type checking terminates]
[8d76f2b]382
[266732e]383Idris is a current, general-purpose dependently typed programming language.
384Length checking is a common benchmark for full dependent type systems.
385Here, the capability being considered is to track lengths that adjust during the execution of a program, such as when an \emph{add} operation produces a collection one element longer than the one on which it started.
386[TODO: finish explaining what Data.Vect is and then the essence of the comparison]
[8d76f2b]387
388POINTS:
[dab9fb93]389here is how our basic checks look (on a system that does not have to compromise);
[8d76f2b]390it can also do these other cool checks, but watch how I can mess with its conservativeness and termination
391
[266732e]392Two current, state-of-the-art array languages, Dex\cite{arr:dex:long} and Futhark\cite{arr:futhark:tytheory}, offer offer novel contributions concerning similar, restricted dependent types for tracking array length.
393Unlike \CFA, both are garbage-collected functional languages.
394Because they are garbage-collected, referential integrity is built-in, meaning that the heavyweight analysis, that \CFA aims to avoid, is unnecessary.
395So, like \CFA, the checking in question is a lightweight bounds-only analysis.
396Like \CFA, their checks that are conservatively limited by forbidding arithmetic in the depended-upon expression.
[8d76f2b]397
398
399
[266732e]400The Futhark work discusses the working language's connection to a lambda calculus, with typing rules and a safety theorem proven in reference to an operational semantics.
401There is a particular emphasis on an existential type, enabling callee-determined return shapes.
402
[8d76f2b]403
404Dex uses a novel conception of size, embedding its quantitative information completely into an ordinary type.
405
[266732e]406Futhark and full-strength dependently typed languages treat array sizes are ordinary values.
407Futhark restricts these expressions syntactically to variables and constants, while a full-strength dependent system does not.
[8d76f2b]408
[266732e]409CFA's hybrid presentation, @forall( [N] )@, has @N@ belonging to the type system, yet has no instances.
410Belonging to the type system means it is inferred at a call site and communicated implicitly, like in Dex and unlike in Futhark.
411Having no instances means there is no type for a variable @i@ that constrains @i@ to be in the range for @N@, unlike Dex, [TODO: verify], but like Futhark.
[8d76f2b]412
413\subsection{Static safety in C extensions}
414
415
416\section{Future Work}
417
418\subsection{Declaration syntax}
419
420\subsection{Range slicing}
421
422\subsection{With a module system}
423
424\subsection{With described enumerations}
425
[266732e]426A project in \CFA's current portfolio will improve enumerations.
427In the incumbent state, \CFA has C's enumerations, unmodified.
428I will not discuss the core of this project, which has a tall mission already, to improve type safety, maintain appropriate C compatibility and offer more flexibility about storage use.
429It also has a candidate stretch goal, to adapt \CFA's @forall@ generic system to communicate generalized enumerations:
[8d76f2b]430\begin{lstlisting}
[266732e]431forall( T | is_enum(T) )
432void show_in_context( T val ) {
433        for( T i ) {
434                string decorator = "";
435                if ( i == val-1 ) decorator = "< ready";
436                if ( i == val   ) decorator = "< go"   ;
437                sout | i | decorator;
438        }
439}
440enum weekday { mon, tue, wed = 500, thu, fri };
441show_in_context( wed );
[8d76f2b]442\end{lstlisting}
443with output
444\begin{lstlisting}
[266732e]445mon
446tue < ready
447wed < go
448thu
449fri
[8d76f2b]450\end{lstlisting}
[266732e]451The details in this presentation aren't meant to be taken too precisely as suggestions for how it should look in \CFA.
452But the example shows these abilities:
[8d76f2b]453\begin{itemize}
[266732e]454\item a built-in way (the @is_enum@ trait) for a generic routine to require enumeration-like information about its instantiating type
455\item an implicit implementation of the trait whenever a user-written enum occurs (@weekday@'s declaration implies @is_enum@)
456\item a total order over the enumeration constants, with predecessor/successor (@val-1@) available, and valid across gaps in values (@tue == 1 && wed == 500 && tue == wed - 1@)
457\item a provision for looping (the @for@ form used) over the values of the type.
[8d76f2b]458\end{itemize}
459
460If \CFA gets such a system for describing the list of values in a type, then \CFA arrays are poised to move from the Futhark level of expressiveness, up to the Dex level.
461
[dab9fb93]462[TODO: introduce Ada in the comparators]
[8d76f2b]463
[266732e]464In Ada and Dex, an array is conceived as a function whose domain must satisfy only certain structural assumptions, while in C, C++, Java, Futhark and \CFA today, the domain is a prefix of the natural numbers.
465The generality has obvious aesthetic benefits for programmers working on scheduling resources to weekdays, and for programmers who prefer to count from an initial number of their own choosing.
[8d76f2b]466
[266732e]467This change of perspective also lets us remove ubiquitous dynamic bound checks.
468[TODO: xref] discusses how automatically inserted bound checks can often be optimized away.
469But this approach is unsatisfying to a programmer who believes she has written code in which dynamic checks are unnecessary, but now seeks confirmation.
470To remove the ubiquitous dynamic checking is to say that an ordinary subscript operation is only valid when it can be statically verified to be in-bound (and so the ordinary subscript is not dynamically checked), and an explicit dynamic check is available when the static criterion is impractical to meet.
[8d76f2b]471
472[TODO, fix confusion:  Idris has this arrangement of checks, but still the natural numbers as the domain.]
473
[266732e]474The structural assumptions required for the domain of an array in Dex are given by the trait (there, ``interface'') @Ix@, which says that the parameter @n@ is a type (which could take an argument like @weekday@) that provides two-way conversion with the integers and a report on the number of values.
475Dex's @Ix@ is analogous the @is_enum@ proposed for \CFA above.
[8d76f2b]476\begin{lstlisting}
477interface Ix n
[266732e]478 get_size n : Unit -> Int
479 ordinal : n -> Int
480 unsafe_from_ordinal n : Int -> n
[8d76f2b]481\end{lstlisting}
482
[266732e]483Dex uses this foundation of a trait (as an array type's domain) to achieve polymorphism over shapes.
484This flavour of polymorphism lets a function be generic over how many (and the order of) dimensions a caller uses when interacting with arrays communicated with this function.
485Dex's example is a routine that calculates pointwise differences between two samples.
486Done with shape polymorphism, one function body is equally applicable to a pair of single-dimensional audio clips (giving a single-dimensional result) and a pair of two-dimensional photographs (giving a two-dimensional result).
487In both cases, but with respectively dimensioned interpretations of ``size,'' this function requires the argument sizes to match, and it produces a result of the that size.
[8d76f2b]488
[266732e]489The polymorphism plays out with the pointwise-difference routine advertising a single-dimensional interface whose domain type is generic.
490In the audio instantiation, the duration-of-clip type argument is used for the domain.
491In the photograph instantiation, it's the tuple-type of $ \langle \mathrm{img\_wd}, \mathrm{img\_ht} \rangle $.
492This use of a tuple-as-index is made possible by the built-in rule for implementing @Ix@ on a pair, given @Ix@ implementations for its elements
[8d76f2b]493\begin{lstlisting}
494instance {a b} [Ix a, Ix b] Ix (a & b)
[266732e]495 get_size = \(). size a * size b
496 ordinal = \(i, j). (ordinal i * size b) + ordinal j
497 unsafe_from_ordinal = \o.
498bs = size b
499(unsafe_from_ordinal a (idiv o bs), unsafe_from_ordinal b (rem o bs))
[8d76f2b]500\end{lstlisting}
501and by a user-provided adapter expression at the call site that shows how to indexing with a tuple is backed by indexing each dimension at a time
502\begin{lstlisting}
[266732e]503img_trans :: (img_wd,img_ht)=>Real
504img_trans.(i,j) = img.i.j
505result = pairwise img_trans
[8d76f2b]506\end{lstlisting}
507[TODO: cite as simplification of example from https://openreview.net/pdf?id=rJxd7vsWPS section 4]
508
509In the case of adapting this pattern to \CFA, my current work provides an adapter from ``successively subscripted'' to ``subscripted by tuple,'' so it is likely that generalizing my adapter beyond ``subscripted by @ptrdiff_t@'' is sufficient to make a user-provided adapter unnecessary.
510
511\subsection{Retire pointer arithmetic}
[82e5670]512
513
514\section{\CFA}
515
516XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
517moved from background chapter \\
518XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
519
520Traditionally, fixing C meant leaving the C-ism alone, while providing a better alternative beside it.
521(For later:  That's what I offer with array.hfa, but in the future-work vision for arrays, the fix includes helping programmers stop accidentally using a broken C-ism.)
522
523\subsection{\CFA features interacting with arrays}
524
525Prior work on \CFA included making C arrays, as used in C code from the wild,
526work, if this code is fed into @cfacc@.
527The quality of this this treatment was fine, with no more or fewer bugs than is typical.
528
529More mixed results arose with feeding these ``C'' arrays into preexisting \CFA features.
530
531A notable success was with the \CFA @alloc@ function,
532which type information associated with a polymorphic return type
533replaces @malloc@'s use of programmer-supplied size information.
534\begin{cfa}
535// C, library
536void * malloc( size_t );
537// C, user
538struct tm * el1 = malloc(      sizeof(struct tm) );
539struct tm * ar1 = malloc( 10 * sizeof(struct tm) );
540
541// CFA, library
542forall( T * ) T * alloc();
543// CFA, user
544tm * el2 = alloc();
545tm (*ar2)[10] = alloc();
546\end{cfa}
547The alloc polymorphic return compiles into a hidden parameter, which receives a compiler-generated argument.
548This compiler's argument generation uses type information from the left-hand side of the initialization to obtain the intended type.
549Using a compiler-produced value eliminates an opportunity for user error.
550
551TODO: fix in following: even the alloc call gives bad code gen: verify it was always this way; walk back the wording about things just working here; assignment (rebind) seems to offer workaround, as in bkgd-cfa-arrayinteract.cfa
552
553Bringing in another \CFA feature, reference types, both resolves a sore spot of the last example, and gives a first example of an array-interaction bug.
554In the last example, the choice of ``pointer to array'' @ar2@ breaks a parallel with @ar1@.
555They are not subscripted in the same way.
556\begin{cfa}
557ar1[5];
558(*ar2)[5];
559\end{cfa}
560Using ``reference to array'' works at resolving this issue.  TODO: discuss connection with Doug-Lea \CC proposal.
561\begin{cfa}
562tm (&ar3)[10] = *alloc();
563ar3[5];
564\end{cfa}
565The implicit size communication to @alloc@ still works in the same ways as for @ar2@.
566
567Using proper array types (@ar2@ and @ar3@) addresses a concern about using raw element pointers (@ar1@), albeit a theoretical one.
568TODO xref C standard does not claim that @ar1@ may be subscripted,
569because no stage of interpreting the construction of @ar1@ has it be that ``there is an \emph{array object} here.''
570But both @*ar2@ and the referent of @ar3@ are the results of \emph{typed} @alloc@ calls,
571where the type requested is an array, making the result, much more obviously, an array object.
572
573The ``reference to array'' type has its sore spots too.
574TODO see also @dimexpr-match-c/REFPARAM_CALL@ (under @TRY_BUG_1@)
575
576TODO: I fixed a bug associated with using an array as a T.  I think.  Did I really?  What was the bug?
Note: See TracBrowser for help on using the repository browser.