source: doc/theses/mike_brooks_MMath/array.tex @ 7ef4438

Last change on this file since 7ef4438 was d0296db6, checked in by Michael Brooks <mlbrooks@…>, 7 weeks ago

Thesis, array, upgrade accordion demo to use data in all arrays

  • Property mode set to 100644
File size: 74.9 KB
Line 
1\chapter{Array}
2\label{c:Array}
3
4
5\section{Introduction}
6\label{s:ArrayIntro}
7
8Arrays in C are possibly the single most misunderstood and incorrectly used feature in the language, resulting in the largest proportion of runtime errors and security violations.
9This chapter describes the new \CFA language and library features that introduce a length-checked array type to the \CFA standard library~\cite{Cforall}.
10
11Specifically, a new \CFA array is declared by instantiating the generic @array@ type,
12much like instantiating any other standard-library generic type (such as @dlist@),
13though using a new style of generic parameter.
14\begin{cfa}
15@array( float, 99 )@ x;                                 $\C[2.75in]{// x contains 99 floats}$
16\end{cfa}
17Here, the arguments to the @array@ type are @float@ (element type) and @99@ (length).
18When this type is used as a function parameter, the type-system requires that a call's argument matches, down to the length.
19\begin{cfa}
20void f( @array( float, 42 )@ & p ) {}   $\C{// p accepts 42 floats}$
21f( x );                                                                 $\C{// statically rejected: types are different, 99 != 42}$
22
23test2.cfa:3:1 error: Invalid application of existing declaration(s) in expression.
24Applying untyped:  Name: f ... to:  Name: x
25\end{cfa}
26Here, the function @f@'s parameter @p@ is declared with length 42.
27The call @f( x )@, with the argument being the previously-declared object, is invalid, because the @array@ lengths @99@ and @42@ do not match.
28
29A function declaration can be polymorphic over these @array@ arguments by using the @forall@ declaration prefix.
30This function @g@'s takes arbitrary type parameter @T@ (familiar) and \emph{dimension parameter} @N@ (new).
31A dimension paramter represents a to-be-determined count of elements, managed by the type system.
32\begin{cfa}
33forall( T, @[N]@ )
34void g( array( T, @N@ ) & p, int i ) {
35        T elem = p[i];                                          $\C{// dynamically checked: requires 0 <= i < N}$
36}
37g( x, 0 );                                                              $\C{// T is float, N is 99, dynamic subscript check succeeds}$
38g( x, 1000 );                                                   $\C{// T is float, N is 99, dynamic subscript check fails}\CRT$
39
40Cforall Runtime error: subscript 1000 exceeds dimension range [0,99) $for$ array 0x555555558020.
41\end{cfa}
42The call @g( x, 0 )@ is valid because @g@ accepts any length of array, where the type system infers @float@ for @T@ and length @99@ for @N@.
43Inferring values for @T@ and @N@ is implicit, without programmer involvement.
44Furthermore, in this case, the runtime subscript @x[0]@ (parameter @i@ being @0@) in @g@ is valid because 0 is in the dimension range $[0,99)$ of argument @x@.
45The call @g( x, 1000 )@ is also accepted through compile time;
46however, this case's subscript, @x[1000]@, generates an error, because @1000@ is outside the dimension range $[0,99)$ of argument @x@.
47
48The generic @array@ type is comparable to the C array type, which \CFA inherits from C.
49Their runtime characteristics are often identical, and some features are available in both.
50For example, assume a caller instantiates @N@ with 42 (discussion about how to follow) in:
51\begin{cfa}
52forall( [N] )
53void declDemo() {
54        float x1[N];                                            $\C{// built-in type ("C array")}$
55        array(float, N) x2;                                     $\C{// type from library}$
56}
57\end{cfa}
58Both of the locally-declared array variables, @x1@ and @x2@, have 42 elements, each element being a @float@.
59The two variables have identical size and layout; they both encapsulate 42-float stack allocations, with no additional ``bookkeeping'' allocations or headers.
60Providing this explicit generic approach requires a significant extension to the \CFA type system to support a full-feature, safe, efficient (space and time) array-type, which forms the foundation for more complex array forms in \CFA.
61
62Admittedly, the @array@ library type (type for @x2@) is syntactically different from its C counterpart.
63A future goal (TODO xref) is to provide the new features upon a built-in type whose syntax approaches C's (declaration style of @x1@).
64Then, the library @array@ type could be removed, giving \CFA a largely uniform array type.
65At present, the C-syntax array gets partial support for the new features, so the generic @array@ is used exclusively when introducing features;
66feature support and C compatibility are revisited in Section ? TODO.
67
68Offering the @array@ type, as a distinct alternative to the C array, is consistent with \CFA's goal of backwards compatibility, \ie virtually all existing C (@gcc@) programs can be compiled by \CFA with only a small number of changes, similar to \CC (@g++@).
69However, a few compatibility-breaking changes to the behaviour of the C array are necessary, both as an implementation convenience and to fix C's lax treatment of arrays.
70Hence, the @array@ type is an opportunity to start from a clean slate and show a cohesive selection of features, making it unnecessary to deal with every inherited complexity of the C array.
71
72In all discussion following, ``C array'' means the types like that of @x@ and ``\CFA array'' means the standard-library @array@ type (instantiations), like the type of @x2@.
73
74My contributions in this chapter are:
75\begin{enumerate}
76\item A type system enhancement that lets polymorphic functions and generic types be parameterized by a numeric value: @forall( [N] )@.
77\item Provide a length-checked array-type in the \CFA standard library, where the array's length is statically managed and dynamically valued.
78\item Provide argument/parameter passing safety for arrays and subscript safety.
79\item TODO: general parking...
80\item Identify the interesting specific abilities available by the new @array@ type.
81\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.
82\end{enumerate}
83
84
85\section{Definitions and design considerations}
86
87
88\subsection{Dependent typing}
89
90
91
92General dependent typing allows the type system to encode arbitrary predicates (e.g. behavioural specifications for functions),
93which is an anti-goal for my work.
94Firstly, this application is strongly associated with pure functional languages,
95where a characterization of the return value (giving it a precise type, generally dependent upon the parameters)
96is a sufficient postcondition.
97In an imperative language like C and \CFA, it is also necessary to discuss side effects,
98for which an even heavier formalism, like separation logic, is required.
99Secondly, TODO: bash Rust.
100TODO: cite the crap out of these claims.
101
102
103
104\section{Features added}
105
106This section shows more about using the \CFA array and dimension parameters, demonstrating their syntax and semantics by way of motivating examples.
107As stated, the core capability of the new array is tracking all dimensions within the type system, where dynamic dimensions are represented using type variables.
108
109By declaring type variables at the front of object declarations, an array dimension is lexically referenceable where it is needed.
110For example, a declaration can share one length, @N@, among a pair of parameters and the return,
111meaning that it requires both input arrays to be of the same length, and guarantees that the result with be of that length as well.
112\lstinput{10-17}{hello-array.cfa}
113This function @f@ does a pointwise comparison of its two input arrays, checking if each pair of numbers is within half a percent of each other, returning the answers in a newly allocated @bool@ array.
114The dynamic allocation of the @ret@ array by preexisting @alloc@ uses the parameterized dimension information implicitly within its @sizeof@ determination, and casts the return type.
115Note that alloc only sees one whole type for its @T@ (which is @f@'s @array(bool, N)@); this type's size is a computation based on @N@.
116\begin{cfa}
117// simplification
118static inline forall( T & | sized(T) )
119T * alloc() {
120        return (T *)malloc( sizeof(T) );
121}
122\end{cfa}
123This example illustrates how the new @array@ type plugs into existing \CFA behaviour by implementing necessary @sized@ assertions needed by other types.
124(@sized@ implies a concrete \vs abstract type with a runtime-available size, exposed as @sizeof@.)
125As a result, there is significant programming safety by making the size accessible and implicit, compared with C's @calloc@ and non-array supporting @memalign@, which take an explicit length parameter not managed by the type system.
126
127\begin{figure}
128\lstinput{30-43}{hello-array.cfa}
129\lstinput{45-48}{hello-array.cfa}
130\caption{\lstinline{f} Harness}
131\label{f:fHarness}
132\end{figure}
133
134\VRef[Figure]{f:fHarness} shows a harness that uses function @f@, illustrating how dynamic values are fed into the @array@ type.
135Here, the dimension of arrays @x@, @y@, and @result@ is specified from a command-line value, @dim@, and these arrays are allocated on the stack.
136Then the @x@ array is initialized with decreasing values, and the @y@ array with amounts offset by constant @0.005@, giving relative differences within tolerance initially and diverging for later values.
137The program main is run (see figure bottom) with inputs @5@ and @7@ for sequence lengths.
138The loops follow the familiar pattern of using the variable @dim@ to iterate through the arrays.
139Most importantly, the type system implicitly captures @dim@ at the call of @f@ and makes it available throughout @f@ as @N@.
140The example shows @dim@ adapting into a type-system managed length at the declarations of @x@, @y@, and @result@, @N@ adapting in the same way at @f@'s loop bound, and a pass-thru use of @dim@ at @f@'s declaration of @ret@.
141Except for the lifetime-management issue of @result@, \ie explicit @free@, this program has eliminated both the syntactic and semantic problems associated with C arrays and their usage.
142The result is a significant improvement in safety and usability.
143
144In general, the @forall( ..., [N] )@ participates in the user-relevant declaration of the name @N@, which becomes usable in parameter/return declarations and within a function.
145The syntactic form is chosen to parallel other @forall@ forms:
146\begin{cfa}
147forall( @[N]@ ) ...     $\C[1.5in]{// dimension}$
148forall( T & ) ...       $\C{// opaque datatype (formerly, "dtype")}$
149forall( T ) ...         $\C{// value datatype (formerly, "otype")}\CRT$
150\end{cfa}
151% The notation @array(thing, N)@ is a single-dimensional case, giving a generic type instance.
152In summary:
153\begin{itemize}
154\item
155@[N]@ within a @forall@ declares the type variable @N@ to be a managed length.
156\item
157@N@ can be used an expression of type @size_t@ within the declared function body.
158\item
159The value of an @N@-expression is the acquired length, derived from the usage site, \ie generic declaration or function call.
160\item
161@array( thing, N0, N1, ... )@ is a multi-dimensional type wrapping $\prod_i N_i$ adjacent occurrences of @thing@-typed objects.
162\end{itemize}
163
164\VRef[Figure]{f:TemplateVsGenericType} shows @N@ is not the same as a @size_t@ declaration in a \CC \lstinline[language=C++]{template}.
165\begin{enumerate}[leftmargin=*]
166\item
167The \CC template @N@ can only be compile-time value, while the \CFA @N@ may be a runtime value.
168% agreed, though already said
169\item
170\CC does not allow a template function to be nested, while \CFA lests its polymorphic functions to be nested.
171% why is this important?
172\item
173The \CC template @N@ must be passed explicitly at the call, unless @N@ has a default value, even when \CC can deduct the type of @T@.
174The \CFA @N@ is part of the array type and passed implicitly at the call.
175% fixed by comparing to std::array
176% mycode/arrr/thesis-examples/check-peter/cs-cpp.cpp, v2
177\item
178\CC cannot have an array of references, but can have an array of pointers.
179\CC has a (mistaken) belief that references are not objects, but pointers are objects.
180In the \CC example, the arrays fall back on C arrays, which have a duality with references with respect to automatic dereferencing.
181The \CFA array is a contiguous object with an address, which can be stored as a reference or pointer.
182% not really about forall-N vs template-N
183% any better CFA support is how Rob left references, not what Mike did to arrays
184% https://stackoverflow.com/questions/1164266/why-are-arrays-of-references-illegal
185% https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references
186\item
187C/\CC arrays cannot be copied, while \CFA arrays can be copied, making them a first-class object (although array copy is often avoided for efficiency).
188% fixed by comparing to std::array
189% mycode/arrr/thesis-examples/check-peter/cs-cpp.cpp, v10
190\end{enumerate}
191TODO: settle Mike's concerns with this comparison (perhaps, remove)
192
193\begin{figure}
194\begin{tabular}{@{}l@{\hspace{20pt}}l@{}}
195\begin{c++}
196
197@template< typename T, size_t N >@
198void copy( T ret[@N@], T x[@N@] ) {
199        for ( int i = 0; i < N; i += 1 ) ret[i] = x[i];
200}
201int main() {
202
203        int ret[10], x[10];
204        for ( int i = 0; i < 10; i += 1 ) x[i] = i;
205        @copy<int, 10 >( ret, x );@
206        for ( int i = 0; i < 10; i += 1 )
207                cout << ret[i] << ' ';
208        cout << endl;
209}
210\end{c++}
211&
212\begin{cfa}
213int main() {
214        @forall( T, [N] )@              // nested function
215        void copy( array( T, @N@ ) & ret, array( T, @N@ ) & x ) {
216                for ( i; N ) ret[i] = x[i];
217        }
218
219        const int n = promptForLength();
220        array( int, n ) ret, x;
221        for ( i; n ) x[i] = i;
222        @copy( ret,  x );@
223        for ( i; n )
224                sout | ret[i] | nonl;
225        sout | nl;
226}
227\end{cfa}
228\end{tabular}
229\caption{\lstinline{N}-style paramters, for \CC template \vs \CFA generic type }
230\label{f:TemplateVsGenericType}
231\end{figure}
232
233Just as the first example in \VRef[Section]{s:ArrayIntro} shows a compile-time rejection of a length mismatch,
234so are length mismatches stopped when they invlove dimension parameters.
235While \VRef[Figure]{f:fHarness} shows successfully calling a function @f@ expecting two arrays of the same length,
236\begin{cfa}
237array( bool, N ) & f( array( float, N ) &, array( float, N ) & );
238\end{cfa}
239a static rejection occurs when attempting to call @f@ with arrays of potentially differing lengths.
240\lstinput[tabsize=1]{70-74}{hello-array.cfa}
241When the argument lengths themselves are statically unknown,
242the static check is conservative and, as always, \CFA's casting lets the programmer use knowledge not shared with the type system.
243\begin{tabular}{@{\hspace{0.5in}}l@{\hspace{1in}}l@{}}
244\lstinput{90-97}{hello-array.cfa}
245&
246\lstinput{110-117}{hello-array.cfa}
247\end{tabular}
248
249\noindent
250This static check's full rules are presented in \VRef[Section]{s:ArrayTypingC}.
251
252Orthogonally, the \CFA array type works within generic \emph{types}, \ie @forall@-on-@struct@.
253The same argument safety and the associated implicit communication of array length occurs.
254Preexisting \CFA allowed aggregate types to be generalized with type parameters, enabling parameterizing for element types.
255Now, \CFA also allows parameterizing them by length.
256Doing so gives a refinement of C's ``flexible array member'' pattern[TODO: cite ARM 6.7.2.1 pp18]\cite{arr:gnu-flex-mbr}.
257While a C flexible array member can only occur at the end of the enclosing structure,
258\CFA allows length-parameterized array members to be nested at arbitrary locations.
259This flexibility, in turn, allows for multiple array members.
260\lstinput{10-15}{hello-accordion.cfa}
261This structure's layout has the starting offset of @studentIds@ varying according to the generic parameter @C@, and the offset of @preferences@ varying according to both generic parameters.
262
263The school example has the data structure capturing many students' course-preference forms.
264It has course- and student-level metadata (their respective display names) and a position-based preferecens' matrix.
265The input files in \VRef[Figure]{f:checkHarness} give example data.
266
267When a function operates on a @School@ structure, the type system handles its memory layout transparently.
268\lstinput{30-37}{hello-accordion.cfa}
269In the running example, this @getPref@ function answers,
270for the student at position @sIx@, what is the position of its @pref@\textsuperscript{th}-favoured class?
271
272\VRef[Figure]{f:checkHarness} shows the @School@ harness and results with different array sizes.
273This example program prints the courses in each student's preferred order, all using the looked-up display names.
274Note the declaration of the @school@ variable.
275It is on the stack and its initialization does not use any casting or size arithmetic.
276Both of these points are impossible with a C flexible array member.
277When heap allocation is preferred, the original pattern still applies.
278\begin{cfa}
279School( classes, students ) * sp = alloc();
280\end{cfa}
281This ability to avoid casting and size arithmetic improves safety and usability over C flexible array members.
282
283
284\begin{figure}
285% super hack to get this to line up
286\begin{tabular}{@{}ll@{\hspace{25pt}}l@{}}
287\begin{tabular}{@{}p{3.25in}@{}}
288\lstinput{50-55}{hello-accordion.cfa}
289\vspace*{-3pt}
290\lstinput{90-98}{hello-accordion.cfa}
291\end{tabular}
292&
293\raisebox{0.32\totalheight}{%
294}%
295&
296\end{tabular}
297
298TODO: Get Peter's layout help
299
300\$ cat school1
301
302\lstinput{}{school1}
303
304\$ ./a.out < school1
305
306\lstinput{}{school1.out}
307
308\$ cat school2
309
310\lstinput{}{school2}
311
312\$ ./a.out < school2
313
314\lstinput{}{school2.out}
315
316\caption{\lstinline{School} harness, input and output}
317\label{f:checkHarness}
318\end{figure}
319
320
321\section{Typing of C Arrays}
322\label{s:ArrayTypingC}
323
324Essential in giving a guarantee of accurate length is the compiler's ability
325to reject a program that presumes to mishandle length.
326By contrast, most discussion so far dealt with communicating length,
327from one party who knows it, to another who is willing to work with any given length.
328For scenarios where the concern is a mishandled length,
329the interaction is between two parties who both claim to know (something about) it.
330Such a scenario occurs in this pure C fragment, wich today's C compilers accept:
331\begin{cfa}
332        int n = @42@;
333        float x[n];
334        float (*xp)[@999@] = &x;
335        (*xp)[@500@];  // in "bound"?
336\end{cfa}
337
338Here, the array @x@ has length 42, while a pointer to it (@xp@) claims length 999.
339So, while the subscript of @xp@ at position 500 is out of bound of its referent @x@,
340the access appears in-bound of the type information available on @xp@.
341Truly, length is being mishandled in the previous step,
342where the type-carried length information on @x@ is not compatible with that of @xp@.
343
344The \CFA new-array rejects the analogous case:
345\begin{cfa}
346        int n = @42@;
347        array(float, n) x;
348        array(float, 999) * xp = x; // static rejection here
349        (*xp)[@500@]; // runtime check vs len 999
350\end{cfa}
351
352% TODO: kill the vertical whitespace around these lists
353% nothing from https://stackoverflow.com/questions/1061112/eliminate-space-before-beginitemize is working
354
355The way the \CFA array is implemented,
356the type analysis of this \CFA case reduces to a case similar to the earlier C version.
357The \CFA compiler's compatibility analysis proceeds as:
358\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
359\item
360        Is @array(float, 999)@ type-compatible with @array(float, n)@?
361\item
362        Is @arrayX(float, char[999])@ type-compatible with @arrayX(float, char[n])@?
363        \footnote{Here, \lstinline{arrayX} represents the type that results
364                from desugaring the \lstinline{array} type
365                into a type whose generic parameters are all types.
366                This presentation elides the noisy fact that
367                \lstinline{array} is actually a macro for something bigger;
368                the reduction to \lstinline{char[-]} still proceeds as sketched.}
369\item
370        Is @char[999]@ type-compatible with @char[n]@?
371\end{itemize}
372
373I chose to achieve the necessary rejection of the \CFA case
374by adding a rejection of the corresponding C case.
375
376This decision is not backward compatible.
377There are two complementary mitigations for this incompatibility.
378
379First, a simple recourse is available to a programmer who intends to proceed
380with the statically unsound assignment.
381This situation might arise if @n@ were known to be 999,
382rather than 42, as in the introductory examples.
383The programmer can add a cast, as in:
384\begin{cfa}
385        xp = ( float (*)[999] ) & x;
386\end{cfa}
387This addition causes \CFA to accept, beacause now, the programmer has accepted blame.
388This addition is benign in plain C, because the cast is valid, just unnecessary there.
389Moreover, the addition can even be seen as appropriate ``eye candy,''
390marking where the unchecked length knowledge is used.
391Therefore, a program being onboarded to \CFA can receive a simple upgrade,
392to satisfy the \CFA rules (and arguably become clearer),
393without giving up its validity to a plain C compiler.
394
395Second, the incompatibility only affects types like pointer-to-array,
396which are are infrequently used in C.
397The more common C idiom for aliasing an array is to use the pointer-to-first-element type,
398which does not participate in the \CFA array's length checking.
399\footnote{Notably, the desugaring of the \lstinline{array@} type,
400        avoids letting any \lstinline{-[-]} type decay,
401        in order to preserve the length information that powers runtime bound checking.}
402Therefore, the frequency of needing to upgrade wild C code (as discussed in the first mitigation)
403is anticipated to be low.
404
405Because the incompatibility represents a low cost to a \CFA onboarding effort
406(with a plausible side benefit of linting the original code for a missing annotation),
407I elected not to add special measures to retain the compatibility.
408It would be possible to flag occurrences of @-[-]@ types that come from @array@ desugaring,
409treating those with stricter \CFA rules, while treating others with classic C rules.
410If future lessons from C project onboarding warrant it,
411this special compatibility measure can be added.
412
413Having allowed that both the initial C example's check
414\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
415        \item
416                Is @float[999]@ type-compatible with @float[n]@?
417\end{itemize}
418and the second \CFA exmple's induced check
419\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
420        \item
421                Is @char[999]@ type-compatible with @char[n]@?
422\end{itemize}
423shall have the same answer, (``no''),
424discussion turns to how I got the \CFA compiler to produce this answer.
425In its preexisting form, it produced a (buggy) approximation of the C rules.
426To implement the new \CFA rules, I took the syntactic recursion a step further, obtaining,
427in both cases:
428\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
429        \item
430                Is @999@ TBD-compatible with @n@?
431\end{itemize}
432This compatibility question applies to a pair of expressions, where the earlier ones were to types.
433Such an expression-compatibility question is a new addition to the \CFA compiler.
434These questions only arise in the context of dimension expressions on (C) array types.
435
436TODO: ensure these compiler implementation matters are treated under \CFA compiler background:
437type unification,
438cost calculation,
439GenPoly.
440
441The relevant technical component of the \CFA compiler is,
442within the type resolver, the type unification procedure.
443I added rules for continuing this unification into expressions that occur within types.
444It is still fundamentally doing \emph{type} unification
445because it is participating in binding type variables,
446and not participating in binding any variables that stand in for expression fragments
447(for there is no such sort of variable in \CFA's analysis.)
448
449An unfortunate fact about the \CFA compiler's preexisting implementation is that
450type unification suffers from two forms of duplication.
451
452The first duplication has (many of) the unification rules stated twice.
453As a result, my additions for dimension expressions are stated twice.
454The extra statement of the rules occurs in the GenPoly module,
455where concrete types like @array(int, 5)@\footnote{
456        Again, the presentation is simplified
457        by leaving the \lstinline{array} macro unexpanded}
458are lowered into corresponding C types @struct __conc_array_1234@ (the suffix being a generated index).
459In this case, the struct's definition gives fields that hardcode the argument values of @float@ and @5@.
460The next time an @array(-,-)@ concrete instance is encountered,
461is the previous @struct __conc_array_1234@ suitable for it?
462Yes, for another occurrance of @array(int, 5)@;
463no, for either @array(rational(int), 5)@ or @array(int, 42)@.
464By the last example, this phase must ``reject''
465the hypothesis that it should reuse the dimension-5 instance's C-lowering for a dimension-42 instance.
466
467The second duplication has unification (proper) being invoked at two stages of expression resolution.
468As a result, my added rule set needs to handle more cases than the preceding discussion motivates.
469In the program
470\begin{cfa}
471        void f( double );
472        forall( T & ) void f( T & );
473        void g( int n ) {
474                array( float, n + 1 ) x;
475                f(x);
476        }
477\end{cfa}
478when resolving the function call, the first unification stage
479compares the types @T@, of the parameter, with @array( float, n + 1 )@, of the argument.
480TODO: finish.
481
482The actual rules for comparing two dimension expressions are conservative.
483To answer, ``yes, consider this pair of expressions to be matching,''
484is to imply, ``all else being equal, allow an array with length calculated by $e_1$
485to be passed to a function expecting a length-$e_2$ array.''\footnote{
486        TODO: Deal with directionality, that I'm doing exact-match, no ``at least as long as,'' no subtyping.
487        Should it be an earlier scoping principle?  Feels like it should matter in more places than here.}
488So, a ``yes'' answer must represent a guarantee that both expressions will evaluate the
489same result, while a ``no'' can tolerate ``they might, but we're not sure,'
490provided that practical recourses are available
491to let programmers express their better knowledge.
492The specific rule-set that I offer with the current release is, in fact, extremely conservative.
493I chose to keep things simple,
494and allow real future needs do drive adding additional complexity,
495within the framework that I laid out.
496
497For starters, the original motivating example's rejection
498is not based on knowledge that
499the @xp@ length of (the literal) 999 is value-unequal to
500the (obvious) runtime value of the variable @n@, which is the @x@ length.
501Rather, the analysis assumes a variable's value can be anything,
502and so there can be no guarantee that its value is 999.
503So, a variable use and a literal can never match.
504
505Two occurrences of the same literal value are obviously a fine match.
506For two occurrences of the same varialbe, more information is needed.
507For example, this one is fine
508\begin{cfa}
509        void f( const int n ) {
510                float x[n];
511                float (*xp)[n] = x; // accept
512        }
513\end{cfa}
514while this one is not:
515\begin{cfa}
516        void f() {
517                int n = 42;
518                float x[n];
519                n = 999;
520                float (*xp)[n] = x; // reject
521        }
522\end{cfa}
523Furthermore, the fact that the first example sees @n@ as @const@
524is not actually a sufficent basis.
525In this example, @f@'s length expression's declaration is as @const@ as it can be,
526yet its value still changes between the two invocations:
527\begin{cfa}
528        // compile unit 1
529        void g();
530        void f( const int & const nr ) {
531                float x[nr];
532                g();
533                float (*xp)[nr] = x; // reject
534        }
535        // compile unit 2
536        static int n = 42;
537        void g() {
538                n = 99;
539        }
540        void f( const int & );
541        int main () {
542                f(n);
543                return 0;
544        }
545\end{cfa}
546The issue in this last case is,
547just because you aren't able to change something doesn't mean someone else can't.
548
549My rule set also respects a feature of the C tradition.
550In spite of the several limitations of the C rules
551accepting cases that produce different values, there are a few mismatches that C stops.
552C is quite precise when working with two static values:
553\begin{cfa}
554        enum { fortytwo = 42 };
555        float x[fortytwo];
556        float (*xp1)[42] = &x; // accept
557        float (*xp2)[999] = &x; // reject
558\end{cfa}
559My \CFA rules agree with C's on these cases.
560
561My rules classify expressions into three groups:
562\begin{description}
563\item[Statically Evaluable]
564        Expressions for which a specific value can be calculated (conservatively)
565        at compile-time.
566        A preexisting \CFA compiler module defines which expressions qualify,
567        and evaluates them.
568        Includes literals and enumeration values.
569\item[Dynamic but Stable]
570        The value of a variable declared as @const@.
571        Includes a @const@ parameter.
572\item[Potentially Unstable]
573        The catch-all category.  Notable examples include:
574        any function-call result (@float x[foo()];@),
575        the particular function-call result that is a pointer dereference (@void f(const int * n) { float x[*n]; }@), and
576        any use of a reference-typed variable.
577\end{description}
578
579My \CFA rules are:
580\begin{itemize}
581\item
582        Accept a Statically Evaluable pair, if both expressions have the same value.
583        Notably, this rule allows a literal to match with an enumeration value, based on the value.
584\item
585        Accept a Dynamic but Stable pair, if both expressions are written out the same, e.g. refers to same variable declaration.
586\item
587        Otherwise, reject.
588        Notably, reject all pairs from the Potentially Unstable group.
589        Notably, reject all pairs that cross groups.
590\end{itemize}
591
592The traditional C rules are:
593\begin{itemize}
594\item
595        Reject a Statically Evaluable pair, if the expressions have two different values.
596\item
597        Otherwise, accept.
598\end{itemize}
599
600
601\newcommand{\falsealarm}{{\color{orange}\small{*}}}
602\newcommand{\allowmisuse}{{\color{red}\textbf{!}}}
603\newcommand{\cmark}{\ding{51}} % from pifont
604\newcommand{\xmark}{\ding{55}}
605\begin{figure}
606        \begin{tabular}{@{}l@{\hspace{16pt}}c@{\hspace{8pt}}c@{\hspace{16pt}}c@{\hspace{8pt}}c@{\hspace{16pt}}c}
607         & \multicolumn{2}{c}{\underline{Values Equal}}
608         & \multicolumn{2}{c}{\underline{Values Unequal}} 
609         & \\
610        \textbf{Case}                                & C      & \CFA                & C                      & \CFA    & Compat. \\
611        Both Statically Evaluable, Same Symbol       & Accept & Accept              &                        &         & \cmark \\
612        Both Statically Evaluable, Different Symbols & Accept & Accept              & Reject                 & Reject  & \cmark \\
613        Both Dynamic but Stable, Same Symbol         & Accept & Accept              &                        &         & \cmark \\
614        Both Dynamic but Stable, Different Symbols   & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark \\
615        Both Potentially Unstable, Same Symbol       & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark \\
616        Any other grouping, Different Symbol         & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark
617        \end{tabular}
618
619        \vspace{12pt}
620        \noindent\textbf{Legend:}
621        \begin{itemize}
622        \item
623                Each row gives the treatment of a test harness of the form
624                \begin{cfa}
625                        float x[ expr1 ];
626                        float (*xp)[ expr2 ] = &x;
627                \end{cfa}
628                where \lstinline{expr1} and \lstinline{expr2} are metavariables varying according to the row's Case.
629                Each row's claim applies to other harnesses too, including,
630                \begin{itemize}
631                \item
632                        calling a function with a paramter like \lstinline{x} and an argument of the \lstinline{xp} type,
633                \item
634                        assignment in place of initialization,
635                \item
636                        using references in place of pointers, and
637                \item
638                        for the \CFA array, calling a polymorphic function on two \lstinline{T}-typed parameters with \lstinline{&x}- and \lstinline{xp}-typed arguments.
639                \end{itemize}
640        \item
641                Each case's claim is symmetric (swapping \lstinline{expr1} with \lstinline{expr2} has no effect),
642                even though most test harnesses are asymetric.
643        \item
644                The table treats symbolic identity (Same/Different on rows)
645                apart from value eqality (Equal/Unequal on columns).
646                \begin{itemize}
647                \item
648                        The expressions \lstinline{1}, \lstinline{0+1} and \lstinline{n}
649                        (where \lstinline{n} is a variable with value 1),
650                        are all different symbols with the value 1.
651                \item
652                        The column distinction expresses ground truth about whether an omniscient analysis should accept or reject.
653                \item
654                        The row distinction expresses the simple static factors used by today's analyses.
655                \end{itemize}
656        \item
657                Accordingly, every Reject under Values Equal is a false alarm (\falsealarm),
658                while every Accept under Values Unequal is an allowed misuse (\allowmisuse).
659        \end{itemize}
660        \caption{Case comparison for array type compatibility, given pairs of dimension expressions.
661                TODO: get Peter's LaTeX help on overall appearance, probably including column spacing/centering and bullet indentation.}
662        \label{f:DimexprRuleCompare}
663\end{figure}
664
665
666Figure~\ref{f:DimexprRuleCompare} gives a case-by-case comparison of the consequences of these rule sets.
667It demonstrates that the \CFA false alarms occur in the same cases as C treats unsafely.
668It also shows that C-incompatibilities only occur in cases that C treats unsafely.
669
670
671The conservatism of the new rule set can leave a programmer needing a recourse,
672when needing to use a dimension expression whose stability argument
673is more subtle than current-state analysis.
674This recourse is to declare an explicit constant for the dimension value.
675Consider these two dimension expressions,
676whose reuses are rejected by the blunt current-state rules:
677\begin{cfa}
678        void f( int & nr, const int nv ) {
679                float x[nr];
680                float (*xp)[nr] = & x; // reject: nr varying (no references)
681                float y[nv + 1];
682                float (*yp)[nv + 1] = & y; // reject: ?+? unpredicable (no functions)
683        }
684\end{cfa}
685Yet, both dimension expressions are reused safely.
686(The @nr@ reference is never written, not volatile
687and control does not leave the function between the uses.
688The name @?+?@ resolves to a function that is quite predictable.)
689The programmer here can add the constant declarations:
690\begin{cfa}
691        void f( int & nr, const int nv ) {
692                @const int nx@ = nr;
693                float x[nx];
694                float (*xp)[nx] = & x; // acept
695                @const int ny@ = nv + 1;
696                float y[ny];
697                float (*yp)[ny] = & y; // accept
698        }
699\end{cfa}
700The result is the originally intended semantics,
701achieved by adding a superfluous ``snapshot it as of now'' directive.
702
703The snapshotting trick is also used by the translation, though to achieve a different outcome.
704Rather obviously, every array must be subscriptable, even a bizzarre one:
705\begin{cfa}
706        array( float, rand(10) ) x;
707        x[0];  // 10% chance of bound-check failure
708\end{cfa}
709Less obvious is that the mechanism of subscripting is a function call,
710which must communicate length accurately.
711The bound-check above (callee logic) must use the actual allocated length of @x@,
712without mistakenly reevaluating the dimension expression, @rand(10)@.
713Adjusting the example to make the function's use of length more explicit:
714\begin{cfa}
715        forall ( T * )
716        void f( T * x ) { sout | sizeof(*x); }
717        float x[ rand(10) ];
718        f( x );
719\end{cfa}
720Considering that the partly translated function declaration is, loosely,
721\begin{cfa}
722        void f( size_t __sizeof_T, void * x ) { sout | __sizeof_T; }
723\end{cfa}
724the translated call must not go like:
725\begin{cfa}
726        float x[ rand(10) ];
727        f( rand(10), &x );
728\end{cfa}
729Rather, its actual translation is like:
730\begin{cfa}
731        size_t __dim_x = rand(10);
732        float x[ __dim_x ];
733        f( __dim_x, &x );
734\end{cfa}
735The occurrence of this dimension hoisting during translation was present in the preexisting \CFA compiler.
736But its cases were buggy, particularly with determining, ``Can hoisting be skipped here?''
737For skipping this hoisting is clearly desirable in some cases,
738not the least of which is when the programmer has already done so manually.
739My work includes getting these cases right, harmonized with the accept/reject criteria, and tested.
740
741
742
743TODO: Discuss the interaction of this dimension hoisting with the challenge of extra unification for cost calculation
744
745\section{Multidimensional Arrays}
746\label{toc:mdimpl}
747
748% TODO: introduce multidimensional array feature and approaches
749
750When working with arrays, \eg linear algebra, array dimensions are referred to as ``rows'' and ``columns'' for a matrix, adding ``planes'' for a cube.
751(There is little terminology for higher dimensional arrays.)
752For example, an acrostic poem\footnote{A type of poetry where the first, last or other letters in a line spell out a particular word or phrase in a vertical column.}
753can be treated as a grid of characters, where the rows are the text and the columns are the embedded keyword(s).
754Within a poem, there is the concept of a \newterm{slice}, \eg a row is a slice for the poem text, a column is a slice for a keyword.
755In general, the dimensioning and subscripting for multidimensional arrays has two syntactic forms: @m[r,c]@ or @m[r][c]@.
756
757Commonly, an array, matrix, or cube, is visualized (especially in mathematics) as a contiguous row, rectangle, or block.
758This conceptualization is reenforced by subscript ordering, \eg $m_{r,c}$ for a matrix and $c_{p,r,c}$ for a cube.
759Few programming languages differ from the mathematical subscript ordering.
760However, computer memory is flat, and hence, array forms are structured in memory as appropriate for the runtime system.
761The closest representation to the conceptual visualization is for an array object to be contiguous, and the language structures this memory using pointer arithmetic to access the values using various subscripts.
762This approach still has degrees of layout freedom, such as row or column major order, \ie juxtaposed rows or columns in memory, even when the subscript order remains fixed.
763For example, programming languages like MATLAB, Fortran, Julia and R store matrices in column-major order since they are commonly used for processing column-vectors in tabular data sets but retain row-major subscripting.
764In general, storage layout is hidden by subscripting, and only appears when passing arrays among different programming languages or accessing specific hardware.
765
766\VRef[Figure]{f:FixedVariable} shows two C90 approaches for manipulating a contiguous matrix.
767Note, C90 does not support VLAs.
768The fixed-dimension approach (left) uses the type system;
769however, it requires all dimensions except the first to be specified at compile time, \eg @m[][6]@, allowing all subscripting stride calculations to be generated with constants.
770Hence, every matrix passed to @fp1@ must have exactly 6 columns but the row size can vary.
771The variable-dimension approach (right) ignores (violates) the type system, \ie argument and parameters types do not match, and subscripting is performed manually using pointer arithmetic in the macro @sub@.
772
773\begin{figure}
774\begin{tabular}{@{}l@{\hspace{40pt}}l@{}}
775\multicolumn{1}{c}{\textbf{Fixed Dimension}} & \multicolumn{1}{c}{\textbf{Variable Dimension}} \\
776\begin{cfa}
777
778void fp1( int rows, int m[][@6@] ) {
779        ...  printf( "%d ", @m[r][c]@ );  ...
780}
781int fm1[4][@6@], fm2[6][@6@]; // no VLA
782// initialize matrixes
783fp1( 4, fm1 ); // implicit 6 columns
784fp1( 6, fm2 );
785\end{cfa}
786&
787\begin{cfa}
788#define sub( m, r, c ) *(m + r * sizeof( m[0] ) + c)
789void fp2( int rows, int cols, int *m ) {
790        ...  printf( "%d ", @sub( m, r, c )@ );  ...
791}
792int vm1[@4@][@4@], vm2[@6@][@8@]; // no VLA
793// initialize matrixes
794fp2( 4, 4, vm1 );
795fp2( 6, 8, vm2 );
796\end{cfa}
797\end{tabular}
798\caption{C90 Fixed \vs Variable Contiguous Matrix Styles}
799\label{f:FixedVariable}
800\end{figure}
801
802Many languages allow multidimensional arrays-of-arrays, \eg in Pascal or \CC.
803\begin{cquote}
804\begin{tabular}{@{}ll@{}}
805\begin{pascal}
806var m : array[0..4, 0..4] of Integer;  (* matrix *)
807type AT = array[0..4] of Integer;  (* array type *)
808type MT = array[0..4] of AT;  (* array of array type *)
809var aa : MT;  (* array of array variable *)
810m@[1][2]@ := 1;   aa@[1][2]@ := 1 (* same subscripting *)
811\end{pascal}
812&
813\begin{c++}
814int m[5][5];
815
816typedef vector< vector<int> > MT;
817MT vm( 5, vector<int>( 5 ) );
818m@[1][2]@ = 1;  aa@[1][2]@ = 1;
819\end{c++}
820\end{tabular}
821\end{cquote}
822The language decides if the matrix and array-of-array are laid out the same or differently.
823For example, an array-of-array may be an array of row pointers to arrays of columns, so the rows may not be contiguous in memory nor even the same length (triangular matrix).
824Regardless, there is usually a uniform subscripting syntax masking the memory layout, even though a language could differentiated between the two forms using subscript syntax, \eg @m[1,2]@ \vs @aa[1][2]@.
825Nevertheless, controlling memory layout can make a difference in what operations are allowed and in performance (caching/NUMA effects).
826
827C also provides non-contiguous arrays-of-arrays.
828\begin{cfa}
829int m[5][5];                                                    $\C{// contiguous}$
830int * aa[5];                                                    $\C{// non-contiguous}$
831\end{cfa}
832both with different memory layout using the same subscripting, and both with different degrees of issues.
833The focus of this work is on the contiguous multidimensional arrays in C.
834The reason is that programmers are often forced to use the more complex array-of-array form when a contiguous array would be simpler, faster, and safer.
835Nevertheless, the C array-of-array form is still important for special circumstances.
836
837\VRef[Figure]{f:ContiguousNon-contiguous} shows the extensions made in C99 for manipulating contiguous \vs non-contiguous arrays.\footnote{C90 also supported non-contiguous arrays.}
838First, VLAs are supported.
839Second, for contiguous arrays, C99 conjoins one or more of the parameters as a downstream dimension(s), \eg @cols@, implicitly using this parameter to compute the row stride of @m@.
840If the declaration of @fc@ is changed to:
841\begin{cfa}
842void fc( int rows, int cols, int m[@rows@][@cols@] ) ...
843\end{cfa}
844it is possible for C to perform bound checking across all subscripting, but it does not.
845While this contiguous-array capability is a step forward, it is still the programmer's responsibility to manually manage the number of dimensions and their sizes, both at the function definition and call sites.
846That is, the array does not automatically carry its structure and sizes for use in computing subscripts.
847While the non-contiguous style in @faa@ looks very similar to @fc@, the compiler only understands the unknown-sized array of row pointers, and it relies on the programmer to traverse the columns in a row correctly with a correctly bounded loop index.
848Specifically, there is no requirement that the rows are the same length, like a poem with different length lines.
849
850\begin{figure}
851\begin{tabular}{@{}ll@{}}
852\multicolumn{1}{c}{\textbf{Contiguous}} & \multicolumn{1}{c}{\textbf{ Non-contiguous}} \\
853\begin{cfa}
854void fc( int rows, @int cols@, int m[ /* rows */ ][@cols@] ) {
855        ...  printf( "%d ", @m[r][c]@ );  ...
856}
857int m@[5][5]@;
858for ( int r = 0; r < 5; r += 1 ) {
859
860        for ( int c = 0; c < 5; c += 1 )
861                m[r][c] = r + c;
862}
863fc( 5, 5, m );
864\end{cfa}
865&
866\begin{cfa}
867void faa( int rows, int cols, int * m[ @/* cols */@ ] ) {
868        ...  printf( "%d ", @m[r][c]@ );  ...
869}
870int @* aa[5]@;  // row pointers
871for ( int r = 0; r < 5; r += 1 ) {
872        @aa[r] = malloc( 5 * sizeof(int) );@ // create rows
873        for ( int c = 0; c < 5; c += 1 )
874                aa[r][c] = r + c;
875}
876faa( 5, 5, aa );
877\end{cfa}
878\end{tabular}
879\caption{C99 Contiguous \vs Non-contiguous Matrix Styles}
880\label{f:ContiguousNon-contiguous}
881\end{figure}
882
883
884\subsection{Multidimensional array implementation}
885
886A multidimensional array implementation has three relevant levels of abstraction, from highest to lowest, where the array occupies \emph{contiguous memory}.
887\begin{enumerate}
888\item
889Flexible-stride memory:
890this model has complete independence between subscripting ordering and memory layout, offering the ability to slice by (provide an index for) any dimension, \eg slice a plane, row, or column, \eg @c[3][*][*]@, @c[3][4][*]@, @c[3][*][5]@.
891\item
892Fixed-stride memory:
893this model binds the first subscript and the first memory layout dimension, offering the ability to slice by (provide an index for) only the coarsest dimension, @m[row][*]@ or @c[plane][*][*]@, \eg slice only by row (2D) or plane (3D).
894After which, subscripting and memory layout are independent.
895\item
896Explicit-displacement memory:
897this model has no awareness of dimensions just the ability to access memory at a distance from a reference point (base-displacement addressing), \eg @x + 23@ or @x[23}@ $\Rightarrow$ 23rd element from the start of @x@.
898A programmer must manually build any notion of dimensions using other tools;
899hence, this style is not offering multidimensional arrays \see{\VRef[Figure]{f:FixedVariable} right example}.
900\end{enumerate}
901
902There is some debate as to whether the abstraction ordering goes $\{1, 2\} < 3$, rather than my numerically-ordering.
903That is, styles 1 and 2 are at the same abstraction level, with 3 offering a limited set of functionality.
904I chose to build the \CFA style-1 array upon a style-2 abstraction.
905(Justification of the decision follows, after the description of the design.)
906
907Style 3 is the inevitable target of any array implementation.
908The hardware offers this model to the C compiler, with bytes as the unit of displacement.
909C offers this model to its programmer as pointer arithmetic, with arbitrary sizes as the unit.
910Casting a multidimensional array as a single-dimensional array/pointer, then using @x[i]@ syntax to access its elements, is still a form of pointer arithmetic.
911
912Now stepping into the implementation of \CFA's new type-1 multidimensional arrays in terms of C's existing type-2 multidimensional arrays, it helps to clarify that even the interface is quite low-level.
913A C/\CFA array interface includes the resulting memory layout.
914The defining requirement of a type-2 system is the ability to slice a column from a column-finest matrix.
915The required memory shape of such a slice is fixed, before any discussion of implementation.
916The implementation presented here is how the \CFA array library wrangles the C type system, to make it do memory steps that are consistent with this layout.
917TODO: do I have/need a presentation of just this layout, just the semantics of -[all]?
918
919The new \CFA standard library @array@ datatype supports richer multidimensional features than C.
920The new array implementation follows C's contiguous approach, \ie @float [r][c]@, with one contiguous object subscripted by coarsely-strided dimensions directly wrapping finely-strided dimensions.
921Beyond what C's array 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.
922
923The following examples use the matrix declaration @array( float, 5, 7 ) m@, loaded with values incremented by $0.1$, when stepping across the length-7 finely-strided column dimension, and stepping across the length-5 coarsely-strided row dimension.
924\par
925\mbox{\lstinput{121-126}{hello-md.cfa}}
926\par\noindent
927The memory layout is 35 contiguous elements with strictly increasing addresses.
928
929A trivial form of slicing extracts a contiguous inner array, within an array-of-arrays.
930As for 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, \eg @m[2]@, giving the third row.
931This action first subscripts away the most coarsely strided dimensions, leaving a result that expects to be subscripted by the more finely strided dimensions, \eg @m[2][3]@, giving the value @2.3@.
932The following is an example slicing a row.
933\lstinput{60-64}{hello-md.cfa}
934\lstinput[aboveskip=0pt]{140-140}{hello-md.cfa}
935
936However, function @print1d@ is asserting too much knowledge about its parameter @r@ for printing either a row slice or a column slice.
937Specifically, declaring the parameter @r@ with type @array@ means that @r@ is contiguous, which is unnecessarily restrictive.
938That is, @r@ need only be of a container type that offers a subscript operator (of type @ptrdiff_t@ $\rightarrow$ @float@) with managed length @N@.
939The new-array library provides the trait @ar@, so-defined.
940With it, the original declaration can be generalized with the same body.
941\lstinput{43-44}{hello-md.cfa}
942\lstinput[aboveskip=0pt]{145-145}{hello-md.cfa}
943The nontrivial slicing in this example now allows passing a \emph{noncontiguous} slice to @print1d@, where the new-array library provides a ``subscript by all'' operation for this purpose.
944In a multi-dimensional subscript operation, any dimension given as @all@ is a placeholder, \ie ``not yet subscripted by a value'', waiting for such a value, implementing the @ar@ trait.
945\lstinput{150-151}{hello-md.cfa}
946
947The example shows @x[2]@ and @x[[2, all]]@ both refer to the same, ``2.*'' slice.
948Indeed, the various @print1d@ calls under discussion access the entry with value @2.3@ as @x[2][3]@, @x[[2,all]][3]@, and @x[[all,3]][2]@.
949This design preserves (and extends) C array semantics by defining @x[[i,j]]@ to be @x[i][j]@ for numeric subscripts, but also for ``subscripting by all''.
950That is:
951\begin{cquote}
952\begin{tabular}{@{}cccccl@{}}
953@x[[2,all]][3]@ & $\equiv$      & @x[2][all][3]@  & $\equiv$    & @x[2][3]@  & (here, @all@ is redundant)  \\
954@x[[all,3]][2]@ & $\equiv$      & @x[all][3][2]@  & $\equiv$    & @x[2][3]@  & (here, @all@ is effective)
955\end{tabular}
956\end{cquote}
957
958Narrating progress through each of the @-[-][-][-]@\footnote{
959The first ``\lstinline{-}'' is a variable expression and the remaining ``\lstinline{-}'' are subscript expressions.}
960expressions gives, firstly, a definition of @-[all]@, and secondly, a generalization of C's @-[i]@.
961Where @all@ is redundant:
962\begin{cquote}
963\begin{tabular}{@{}ll@{}}
964@x@  & 2-dimensional, want subscripts for coarse then fine \\
965@x[2]@  & 1-dimensional, want subscript for fine; lock coarse == 2 \\
966@x[2][all]@  & 1-dimensional, want subscript for fine \\
967@x[2][all][3]@  & 0-dimensional; lock fine == 3
968\end{tabular}
969\end{cquote}
970Where @all@ is effective:
971\begin{cquote}
972\begin{tabular}{@{}ll@{}}
973@x@  & 2-dimensional, want subscripts for coarse then fine \\
974@x[all]@  & 2-dimensional, want subscripts for fine then coarse \\
975@x[all][3]@  & 1-dimensional, want subscript for coarse; lock fine == 3 \\
976@x[all][3][2]@  & 0-dimensional; lock coarse == 2
977\end{tabular}
978\end{cquote}
979The semantics of @-[all]@ is to dequeue from the front of the ``want subscripts'' list and re-enqueue at its back.
980For example, in a two dimensional matrix, this semantics conceptually transposes the matrix by reversing the subscripts.
981The semantics of @-[i]@ is to dequeue from the front of the ``want subscripts'' list and lock its value to be @i@.
982
983Contiguous arrays, and slices of them, are all represented by the same underlying parameterized type, which includes stride information in its metatdata.
984\PAB{Do not understand this sentence: The \lstinline{-[all]} operation is a conversion from a reference to one instantiation to a reference to another instantiation.}
985The running example's @all@-effective step, stated more concretely, is:
986\begin{cquote}
987\begin{tabular}{@{}ll@{}}
988@x@       & : 5 of ( 7 of @float@ each spaced 1 @float@ apart ) each spaced 7 @floats@ apart \\
989@x[all]@  & : 7 of ( 5 of @float@ each spaced 7 @float@s apart ) each spaced 1 @float@ apart
990\end{tabular}
991\end{cquote}
992
993\begin{figure}
994\includegraphics{measuring-like-layout}
995\caption{Visualization of subscripting by value and by \lstinline[language=CFA]{all}, for \lstinline{x} of type \lstinline{array( float, 5, 7 )} understood as 5 rows by 7 columns.
996The horizontal layout represents contiguous memory addresses while the vertical layout is conceptual.
997The vertical shaded band highlights the location of the targeted element, 2.3.
998Any such vertical slice contains various interpretations of a single address.}
999\label{fig:subscr-all}
1000\end{figure}
1001
1002Figure~\ref{fig:subscr-all} shows one element (in the shaded band) accessed two different ways: as @x[2][3]@ and as @x[all][3][2]@.
1003In both cases, value 2 selects from the coarser dimension (rows of @x@),
1004while the value 3 selects from the finer dimension (columns of @x@).
1005The figure illustrates the value of each subexpression, comparing how numeric subscripting proceeds from @x@, \vs from @x[all]@.
1006Proceeding from @x@ gives the numeric indices as coarse then fine, while proceeding from @x[all]@ gives them fine then coarse.
1007These two starting expressions, which are the example's only multidimensional subexpressions
1008(those that received zero numeric indices so far), are illustrated with vertical steps where a \emph{first} numeric index would select.
1009
1010The figure's presentation offers an intuition answering to: What is an atomic element of @x[all]@?
1011From there, @x[all]@ itself is simply a two-dimensional array, in the strict C sense, of these building blocks.
1012An atom (like the bottommost value, @x[all][3][2]@), is the contained value (in the square box)
1013and a lie about its size (the left diagonal above it, growing upward).
1014An array of these atoms (like the intermediate @x[all][3]@) is just a contiguous arrangement of them, done according to their size;
1015call such an array a column.
1016A column is almost ready to be arranged into a matrix;
1017it is the \emph{contained value} of the next-level building block, but another lie about size is required.
1018At first, an atom needs to be arranged as if it were bigger, but now a column needs to be arranged as if it is smaller (the left diagonal above it, shrinking upward).
1019These lying columns, arranged contiguously according to their size (as announced) form the matrix @x[all]@.
1020Because @x[all]@ takes indices, first for the fine stride, then for the coarse stride, it achieves the requirement of representing the transpose of @x@.
1021Yet every time the programmer presents an index, a C-array subscript is achieving the offset calculation.
1022
1023In the @x[all]@ case, after the finely strided subscript is done (column 3 is selected),
1024the locations referenced by the coarse subscript options (rows 0..4) are offset by 3 floats,
1025compared with where analogous rows appear when the row-level option is presented for @x@.
1026
1027For example, in \lstinline{x[all]}, the shaded band touches atoms 2.0, 2.1, 2.2, 2.3, 1.4, 1.5 and 1.6 (left diagonal).
1028But only the atom 2.3 is storing its value there.
1029The rest are lying about (conflicting) claims on this location, but never exercising these alleged claims.
1030
1031Lying is implemented as casting.
1032The arrangement just described is implemented in the structure @arpk@.
1033This structure uses one type in its internal field declaration and offers a different type as the return of its subscript operator.
1034The field within is a plain-C array of the fictional type, which is 7 floats long for @x[all][3][2]@ and 1 float long for @x[all][3]@.
1035The subscript operator presents what is really inside, by casting to the type below the left diagonal of the lie.
1036
1037%  Does x[all] have to lie too?  The picture currently glosses over how it it advertises a size of 7 floats.  I'm leaving that as an edge case benignly misrepresented in the picture.  Edge cases only have to be handled right in the code.
1038
1039Casting, overlapping, and lying are unsafe.
1040The mission is to implement a style-1 feature in the type system for safe use by a programmer.
1041The offered style-1 system is allowed to be internally unsafe,
1042just as C's implementation of a style-2 system (upon a style-3 system) is unsafe within, even when the programmer is using it without casts or pointer arithmetic.
1043Having a style-1 system relieves the programmer from resorting to unsafe pointer arithmetic when working with noncontiguous slices.
1044
1045% PAB: repeat from previous paragraph.
1046% The choice to implement this style-1 system upon C's style-2 arrays, rather than its style-3 pointer arithmetic, reduces the attack surface of unsafe code.
1047% My casting is unsafe, but I do not do any pointer arithmetic.
1048% When a programmer works in the common-case style-2 subset (in the no-@[all]@ top of Figure~\ref{fig:subscr-all}), my casts are identities, and the C compiler is doing its usual displacement calculations.
1049% If I had implemented my system upon style-3 pointer arithmetic, then this common case would be circumventing C's battle-hardened displacement calculations in favour of my own.
1050
1051% \noindent END: Paste looking for a home
1052
1053The new-array library defines types and operations that ensure proper elements are accessed soundly in spite of the overlapping.
1054The @arpk@ structure and its @-[i]@ operator are defined as:
1055\begin{cfa}
1056forall(
1057        [N],                                    $\C{// length of current dimension}$
1058        S & | sized(S),                 $\C{// masquerading-as}$
1059        Timmed &,                               $\C{// immediate element, often another array}$
1060        Tbase &                                 $\C{// base element, e.g. float, never array}$
1061) { // distribute forall to each element
1062        struct arpk {
1063                S strides[N];           $\C{// so that sizeof(this) is N of S}$
1064        };
1065        // expose Timmed, stride by S
1066        static inline Timmed & ?[?]( arpk( N, S, Timmed, Tbase ) & a, long int i ) {
1067                subcheck( a, i, 0, N );
1068                return (Timmed &)a.strides[i];
1069        }
1070}
1071\end{cfa}
1072The private @arpk@ structure (array with explicit packing) is generic over four types: dimension length, masquerading-as, ...
1073This structure's public interface is hidden behind the @array(...)@ macro and the subscript operator.
1074Construction by @array@ initializes the masquerading-as type information to be equal to the contained-element information.
1075Subscripting by @all@ rearranges the order of masquerading-as types to achieve, in general, nontrivial striding.
1076Subscripting 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.
1077
1078An 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, ...)@.
1079In the base case, @array(E_base)@ is just @E_base@.
1080Because this construction uses the same value for the generic parameters @S@ and @E_im@, the resulting layout has trivial strides.
1081
1082Subscripting 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.
1083Expressed as an operation on types, this rotation is:
1084\begin{eqnarray*}
1085suball( arpk(N, S, E_i, E_b) ) & = & enq( N, S, E_i, E_b ) \\
1086enq( N, S, E_b, E_b ) & = & arpk( N, S, E_b, E_b ) \\
1087enq( N, S, arpk(N', S', E_i', E_b), E_b ) & = & arpk( N', S', enq(N, S, E_i', E_b), E_b )
1088\end{eqnarray*}
1089
1090
1091\section{Bound checks, added and removed}
1092
1093\CFA array subscripting is protected with runtime bound checks.
1094Having dependent typing causes the optimizer to remove more of these bound checks than it would without them.
1095This section provides a demonstration of the effect.
1096
1097The experiment compares the \CFA array system with the padded-room system [TODO:xref] most typically exemplified by Java arrays, but also reflected in the \CC pattern where restricted vector usage models a checked array.
1098The 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.
1099The experiment compares with the \CC version to keep access to generated assembly code simple.
1100
1101As a control case, a simple loop (with no reused dimension sizes) is seen to get the same optimization treatment in both the \CFA and \CC versions.
1102When 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.
1103But 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.
1104
1105TODO: paste source and assembly codes
1106
1107Incorporating reuse among dimension sizes is seen to give \CFA an advantage at being optimized.
1108The case is naive matrix multiplication over a row-major encoding.
1109
1110TODO: paste source codes
1111
1112
1113
1114
1115
1116\section{Comparison with other arrays}
1117
1118
1119\subsection{Rust}
1120
1121\CFA's array is the first lightweight application of dependently-typed bound tracking to an extension of C.
1122Other extensions of C that apply dependently-typed bound tracking are heavyweight, in that the bound tracking is part of a linearly-typed ownership-system, which further helps guarantee statically the validity of every pointer deference.
1123These systems, therefore, ask the programmer to convince the type checker that every pointer dereference is valid.
1124\CFA imposes the lighter-weight obligation, with the more limited guarantee, that initially-declared bounds are respected thereafter.
1125
1126\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.
1127Other 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.
1128The \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.
1129
1130
1131\subsection{Java}
1132
1133Java arrays are arrays-of-arrays because all objects are references \see{\VRef{toc:mdimpl}}.
1134For each array, Java implicitly storages the array dimension in a descriptor, supporting array length, subscript checking, and allowing dynamically-sized array-parameter declarations.
1135\begin{cquote}
1136\begin{tabular}{rl}
1137C      &  @void f( size_t n, size_t m, float x[n][m] );@ \\
1138Java   &  @void f( float x[][] );@
1139\end{tabular}
1140\end{cquote}
1141However, in the C prototype, the parameters @n@ and @m@  are documentation only as the intended size of the first and second dimension of @x@.
1142\VRef[Figure]{f:JavaVsCTriangularMatrix} compares a triangular matrix (array-of-arrays) in dynamically safe Java to unsafe C.
1143Each dynamically sized row in Java stores its dimension, while C requires the programmer to manage these sizes explicitly (@rlnth@).
1144All subscripting is Java has bounds checking, while C has none.
1145Both Java and C require explicit null checking, otherwise there is a runtime failure.
1146
1147\begin{figure}
1148\setlength{\tabcolsep}{15pt}
1149\begin{tabular}{ll@{}}
1150\begin{java}
1151int m[][] = {  // triangular matrix
1152        new int [4],
1153        new int [3],
1154        new int [2],
1155        new int [1],
1156        null
1157};
1158
1159for ( int r = 0; r < m.length; r += 1 ) {
1160        if ( m[r] == null ) continue;
1161        for ( int c = 0; c < m[r].length; c += 1 ) {
1162                m[r][c] = c + r; // subscript checking
1163        }
1164
1165}
1166
1167for ( int r = 0; r < m.length; r += 1 ) {
1168        if ( m[r] == null ) {
1169                System.out.println( "null row" );
1170                continue;
1171        }
1172        for ( int c = 0; c < m[r].length; c += 1 ) {
1173                System.out.print( m[r][c] + " " );
1174        }
1175        System.out.println();
1176
1177}
1178\end{java}
1179&
1180\begin{cfa}
1181int * m[5] = {  // triangular matrix
1182        calloc( 4, sizeof(int) ),
1183        calloc( 3, sizeof(int) ),
1184        calloc( 2, sizeof(int) ),
1185        calloc( 1, sizeof(int) ),
1186        NULL
1187};
1188int rlnth = 4;
1189for ( int r = 0; r < 5; r += 1 ) {
1190        if ( m[r] == NULL ) continue;
1191        for ( int c = 0; c < rlnth; c += 1 ) {
1192                m[r][c] = c + r; // no subscript checking
1193        }
1194        rlnth -= 1;
1195}
1196rlnth = 4;
1197for ( int r = 0; r < 5; r += 1 ) {
1198        if ( m[r] == NULL ) {
1199                printf( "null row\n" );
1200                continue;
1201        }
1202        for ( int c = 0; c < rlnth; c += 1 ) {
1203                printf( "%d ", m[r][c] );
1204        }
1205        printf( "\n" );
1206        rlnth -= 1;
1207}
1208\end{cfa}
1209\end{tabular}
1210\caption{Java (left) \vs C (right) Triangular Matrix}
1211\label{f:JavaVsCTriangularMatrix}
1212\end{figure}
1213
1214The downside of the arrays-of-arrays approach is performance due to pointer chasing versus pointer arithmetic for a contiguous arrays.
1215Furthermore, there is the cost of managing the implicit array descriptor.
1216It is unlikely that a JIT can dynamically rewrite an arrays-of-arrays form into a contiguous form.
1217
1218
1219\subsection{\CC}
1220
1221Because C arrays are difficult and dangerous, the mantra for \CC programmers is to use @std::vector@ in place of the C array.
1222While the vector size can grow and shrink dynamically, \vs a fixed-size dynamic size with VLAs, the cost of this extra feature is mitigated by preallocating the maximum size (like the VLA) at the declaration (one dynamic call) to avoid using @push_back@.
1223\begin{c++}
1224vector< vector< int > > m( 5, vector<int>(8) ); // initialize size of 5 x 8 with 6 dynamic allocations
1225\end{c++}
1226Multidimensional arrays are arrays-of-arrays with associated costs.
1227Each @vector@ array has an array descriptor contain the dimension, which allows bound checked using @x.at(i)@ in place of @x[i]@.
1228Used with these restrictions, out-of-bound accesses are caught, and in-bound accesses never exercise the vector's ability to grow, preventing costly reallocate and copy, and never invalidate references to contained values.
1229This scheme matches Java's safety and expressiveness exactly, but with the inherent costs.
1230
1231
1232\subsection{Levels of dependently typed arrays}
1233
1234The \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:
1235\begin{itemize}
1236\item a \emph{zip}-style operation that consumes two arrays of equal length
1237\item a \emph{map}-style operation whose produced length matches the consumed length
1238\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
1239\end{itemize}
1240Across 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.
1241Along the way, the \CFA array also closes the safety gap (with respect to bounds) that Java has over C.
1242
1243Dependent type systems, considered for the purpose of bound-tracking, can be full-strength or restricted.
1244In a full-strength dependent type system, a type can encode an arbitrarily complex predicate, with bound-tracking being an easy example.
1245The tradeoff of this expressiveness is complexity in the checker, even typically, a potential for its nontermination.
1246In 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.
1247[TODO: clarify how even Idris type checking terminates]
1248
1249Idris is a current, general-purpose dependently typed programming language.
1250Length checking is a common benchmark for full dependent type systems.
1251Here, 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.
1252[TODO: finish explaining what Data.Vect is and then the essence of the comparison]
1253
1254POINTS:
1255here is how our basic checks look (on a system that does not have to compromise);
1256it can also do these other cool checks, but watch how I can mess with its conservativeness and termination
1257
1258Two current, state-of-the-art array languages, Dex\cite{arr:dex:long} and Futhark\cite{arr:futhark:tytheory}, offer novel contributions concerning similar, restricted dependent types for tracking array length.
1259Unlike \CFA, both are garbage-collected functional languages.
1260Because they are garbage-collected, referential integrity is built-in, meaning that the heavyweight analysis, that \CFA aims to avoid, is unnecessary.
1261So, like \CFA, the checking in question is a lightweight bounds-only analysis.
1262Like \CFA, their checks that are conservatively limited by forbidding arithmetic in the depended-upon expression.
1263
1264
1265
1266The 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.
1267There is a particular emphasis on an existential type, enabling callee-determined return shapes.
1268
1269
1270Dex uses a novel conception of size, embedding its quantitative information completely into an ordinary type.
1271
1272Futhark and full-strength dependently typed languages treat array sizes are ordinary values.
1273Futhark restricts these expressions syntactically to variables and constants, while a full-strength dependent system does not.
1274
1275\CFA's hybrid presentation, @forall( [N] )@, has @N@ belonging to the type system, yet has no instances.
1276Belonging to the type system means it is inferred at a call site and communicated implicitly, like in Dex and unlike in Futhark.
1277Having 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.
1278
1279\subsection{Static safety in C extensions}
1280
1281
1282\section{Future work}
1283
1284\subsection{Declaration syntax}
1285
1286\subsection{Range slicing}
1287
1288\subsection{With a module system}
1289
1290\subsection{With described enumerations}
1291
1292A project in \CFA's current portfolio will improve enumerations.
1293In the incumbent state, \CFA has C's enumerations, unmodified.
1294I 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.
1295It also has a candidate stretch goal, to adapt \CFA's @forall@ generic system to communicate generalized enumerations:
1296\begin{cfa}
1297forall( T | is_enum(T) )
1298void show_in_context( T val ) {
1299        for( T i ) {
1300                string decorator = "";
1301                if ( i == val-1 ) decorator = "< ready";
1302                if ( i == val   ) decorator = "< go"   ;
1303                sout | i | decorator;
1304        }
1305}
1306enum weekday { mon, tue, wed = 500, thu, fri };
1307show_in_context( wed );
1308\end{cfa}
1309with output
1310\begin{cfa}
1311mon
1312tue < ready
1313wed < go
1314thu
1315fri
1316\end{cfa}
1317The details in this presentation aren't meant to be taken too precisely as suggestions for how it should look in \CFA.
1318But the example shows these abilities:
1319\begin{itemize}
1320\item a built-in way (the @is_enum@ trait) for a generic routine to require enumeration-like information about its instantiating type
1321\item an implicit implementation of the trait whenever a user-written enum occurs (@weekday@'s declaration implies @is_enum@)
1322\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@)
1323\item a provision for looping (the @for@ form used) over the values of the type.
1324\end{itemize}
1325
1326If \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.
1327
1328[TODO: introduce Ada in the comparators]
1329
1330In Ada and Dex, an array is conceived as a function whose domain must satisfy only certain structural assumptions, while in C, \CC, Java, Futhark and \CFA today, the domain is a prefix of the natural numbers.
1331The 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.
1332
1333This change of perspective also lets us remove ubiquitous dynamic bound checks.
1334[TODO: xref] discusses how automatically inserted bound checks can often be optimized away.
1335But this approach is unsatisfying to a programmer who believes she has written code in which dynamic checks are unnecessary, but now seeks confirmation.
1336To 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.
1337
1338[TODO, fix confusion:  Idris has this arrangement of checks, but still the natural numbers as the domain.]
1339
1340The 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.
1341Dex's @Ix@ is analogous the @is_enum@ proposed for \CFA above.
1342\begin{cfa}
1343interface Ix n
1344get_size n : Unit -> Int
1345ordinal : n -> Int
1346unsafe_from_ordinal n : Int -> n
1347\end{cfa}
1348
1349Dex uses this foundation of a trait (as an array type's domain) to achieve polymorphism over shapes.
1350This 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.
1351Dex's example is a routine that calculates pointwise differences between two samples.
1352Done 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).
1353In 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.
1354
1355The polymorphism plays out with the pointwise-difference routine advertising a single-dimensional interface whose domain type is generic.
1356In the audio instantiation, the duration-of-clip type argument is used for the domain.
1357In the photograph instantiation, it's the tuple-type of $ \langle \mathrm{img\_wd}, \mathrm{img\_ht} \rangle $.
1358This 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
1359\begin{cfa}
1360instance {a b} [Ix a, Ix b] Ix (a & b)
1361get_size = \(). size a * size b
1362ordinal = \(i, j). (ordinal i * size b) + ordinal j
1363unsafe_from_ordinal = \o.
1364bs = size b
1365(unsafe_from_ordinal a (idiv o bs), unsafe_from_ordinal b (rem o bs))
1366\end{cfa}
1367and 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
1368\begin{cfa}
1369img_trans :: (img_wd,img_ht)=>Real
1370img_trans.(i,j) = img.i.j
1371result = pairwise img_trans
1372\end{cfa}
1373[TODO: cite as simplification of example from https://openreview.net/pdf?id=rJxd7vsWPS section 4]
1374
1375In 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.
1376
1377\subsection{Retire pointer arithmetic}
1378
1379
1380\section{\CFA}
1381
1382XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
1383moved from background chapter \\
1384XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
1385
1386Traditionally, fixing C meant leaving the C-ism alone, while providing a better alternative beside it.
1387(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.)
1388
1389\subsection{\CFA features interacting with arrays}
1390
1391Prior work on \CFA included making C arrays, as used in C code from the wild,
1392work, if this code is fed into @cfacc@.
1393The quality of this this treatment was fine, with no more or fewer bugs than is typical.
1394
1395More mixed results arose with feeding these ``C'' arrays into preexisting \CFA features.
1396
1397A notable success was with the \CFA @alloc@ function,
1398which type information associated with a polymorphic return type
1399replaces @malloc@'s use of programmer-supplied size information.
1400\begin{cfa}
1401// C, library
1402void * malloc( size_t );
1403// C, user
1404struct tm * el1 = malloc( sizeof(struct tm) );
1405struct tm * ar1 = malloc( 10 * sizeof(struct tm) );
1406
1407// CFA, library
1408forall( T * ) T * alloc();
1409// CFA, user
1410tm * el2 = alloc();
1411tm (*ar2)[10] = alloc();
1412\end{cfa}
1413The alloc polymorphic return compiles into a hidden parameter, which receives a compiler-generated argument.
1414This compiler's argument generation uses type information from the left-hand side of the initialization to obtain the intended type.
1415Using a compiler-produced value eliminates an opportunity for user error.
1416
1417TODO: 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
1418
1419Bringing 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.
1420In the last example, the choice of ``pointer to array'' @ar2@ breaks a parallel with @ar1@.
1421They are not subscripted in the same way.
1422\begin{cfa}
1423ar1[5];
1424(*ar2)[5];
1425\end{cfa}
1426Using ``reference to array'' works at resolving this issue.  TODO: discuss connection with Doug-Lea \CC proposal.
1427\begin{cfa}
1428tm (&ar3)[10] = *alloc();
1429ar3[5];
1430\end{cfa}
1431The implicit size communication to @alloc@ still works in the same ways as for @ar2@.
1432
1433Using proper array types (@ar2@ and @ar3@) addresses a concern about using raw element pointers (@ar1@), albeit a theoretical one.
1434TODO xref C standard does not claim that @ar1@ may be subscripted,
1435because no stage of interpreting the construction of @ar1@ has it be that ``there is an \emph{array object} here.''
1436But both @*ar2@ and the referent of @ar3@ are the results of \emph{typed} @alloc@ calls,
1437where the type requested is an array, making the result, much more obviously, an array object.
1438
1439The ``reference to array'' type has its sore spots too.
1440TODO see also @dimexpr-match-c/REFPARAM_CALL@ (under @TRY_BUG_1@)
1441
1442TODO: 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.