source: doc/theses/mike_brooks_MMath/array.tex @ 720eec9

Last change on this file since 720eec9 was 720eec9, checked in by Michael Brooks <mlbrooks@…>, 6 days ago

Thesis, array, proofread intro sections.

  • Property mode set to 100644
File size: 74.3 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.
262For a function that operates on a @School@ structure, the type system handles this memory layout transparently.
263\lstinput{40-45}{hello-accordion.cfa}
264\VRef[Figure]{f:checkHarness} shows the @School@ harness and results with different array sizes.
265Note the declaration of the @school@ variable.
266It is on the stack and its initialization does not use any casting or size arithmetic.
267Both of these points are impossible with a C flexible array member.
268When heap allocation is preferred, the original pattern still applies.
269\begin{cfa}
270School( classes, students ) * sp = alloc();
271\end{cfa}
272This ability to avoid casting and size arithmetic improves safety and usability over C flexible array members.
273
274
275\begin{figure}
276% super hack to get this to line up
277\begin{tabular}{@{}ll@{\hspace{25pt}}l@{}}
278\begin{tabular}{@{}p{3.25in}@{}}
279\lstinput{60-64}{hello-accordion.cfa}
280\vspace*{-3pt}
281\lstinput{73-80}{hello-accordion.cfa}
282\end{tabular}
283&
284\raisebox{0.32\totalheight}{%
285\lstinput{85-93}{hello-accordion.cfa}
286}%
287&
288\lstinput{95-109}{hello-accordion.cfa}
289\end{tabular}
290\caption{\lstinline{school} Harness and Output}
291\label{f:checkHarness}
292\end{figure}
293
294
295\section{Typing of C Arrays}
296\label{s:ArrayTypingC}
297
298Essential in giving a guarantee of accurate length is the compiler's ability
299to reject a program that presumes to mishandle length.
300By contrast, most discussion so far dealt with communicating length,
301from one party who knows it, to another who is willing to work with any given length.
302For scenarios where the concern is a mishandled length,
303the interaction is between two parties who both claim to know (something about) it.
304Such a scenario occurs in this pure C fragment, wich today's C compilers accept:
305\begin{cfa}
306        int n = @42@;
307        float x[n];
308        float (*xp)[@999@] = &x;
309        (*xp)[@500@];  // in "bound"?
310\end{cfa}
311
312Here, the array @x@ has length 42, while a pointer to it (@xp@) claims length 999.
313So, while the subscript of @xp@ at position 500 is out of bound of its referent @x@,
314the access appears in-bound of the type information available on @xp@.
315Truly, length is being mishandled in the previous step,
316where the type-carried length information on @x@ is not compatible with that of @xp@.
317
318The \CFA new-array rejects the analogous case:
319\begin{cfa}
320        int n = @42@;
321        array(float, n) x;
322        array(float, 999) * xp = x; // static rejection here
323        (*xp)[@500@]; // runtime check vs len 999
324\end{cfa}
325
326% TODO: kill the vertical whitespace around these lists
327% nothing from https://stackoverflow.com/questions/1061112/eliminate-space-before-beginitemize is working
328
329The way the \CFA array is implemented,
330the type analysis of this \CFA case reduces to a case similar to the earlier C version.
331The \CFA compiler's compatibility analysis proceeds as:
332\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
333\item
334        Is @array(float, 999)@ type-compatible with @array(float, n)@?
335\item
336        Is @arrayX(float, char[999])@ type-compatible with @arrayX(float, char[n])@?
337        \footnote{Here, \lstinline{arrayX} represents the type that results
338                from desugaring the \lstinline{array} type
339                into a type whose generic parameters are all types.
340                This presentation elides the noisy fact that
341                \lstinline{array} is actually a macro for something bigger;
342                the reduction to \lstinline{char[-]} still proceeds as sketched.}
343\item
344        Is @char[999]@ type-compatible with @char[n]@?
345\end{itemize}
346
347I chose to achieve the necessary rejection of the \CFA case
348by adding a rejection of the corresponding C case.
349
350This decision is not backward compatible.
351There are two complementary mitigations for this incompatibility.
352
353First, a simple recourse is available to a programmer who intends to proceed
354with the statically unsound assignment.
355This situation might arise if @n@ were known to be 999,
356rather than 42, as in the introductory examples.
357The programmer can add a cast, as in:
358\begin{cfa}
359        xp = ( float (*)[999] ) & x;
360\end{cfa}
361This addition causes \CFA to accept, beacause now, the programmer has accepted blame.
362This addition is benign in plain C, because the cast is valid, just unnecessary there.
363Moreover, the addition can even be seen as appropriate ``eye candy,''
364marking where the unchecked length knowledge is used.
365Therefore, a program being onboarded to \CFA can receive a simple upgrade,
366to satisfy the \CFA rules (and arguably become clearer),
367without giving up its validity to a plain C compiler.
368
369Second, the incompatibility only affects types like pointer-to-array,
370which are are infrequently used in C.
371The more common C idiom for aliasing an array is to use the pointer-to-first-element type,
372which does not participate in the \CFA array's length checking.
373\footnote{Notably, the desugaring of the \lstinline{array@} type,
374        avoids letting any \lstinline{-[-]} type decay,
375        in order to preserve the length information that powers runtime bound checking.}
376Therefore, the frequency of needing to upgrade wild C code (as discussed in the first mitigation)
377is anticipated to be low.
378
379Because the incompatibility represents a low cost to a \CFA onboarding effort
380(with a plausible side benefit of linting the original code for a missing annotation),
381I elected not to add special measures to retain the compatibility.
382It would be possible to flag occurrences of @-[-]@ types that come from @array@ desugaring,
383treating those with stricter \CFA rules, while treating others with classic C rules.
384If future lessons from C project onboarding warrant it,
385this special compatibility measure can be added.
386
387Having allowed that both the initial C example's check
388\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
389        \item
390                Is @float[999]@ type-compatible with @float[n]@?
391\end{itemize}
392and the second \CFA exmple's induced check
393\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
394        \item
395                Is @char[999]@ type-compatible with @char[n]@?
396\end{itemize}
397shall have the same answer, (``no''),
398discussion turns to how I got the \CFA compiler to produce this answer.
399In its preexisting form, it produced a (buggy) approximation of the C rules.
400To implement the new \CFA rules, I took the syntactic recursion a step further, obtaining,
401in both cases:
402\begin{itemize}[noitemsep,partopsep=-\parskip,parsep=0pt,leftmargin=4em]
403        \item
404                Is @999@ TBD-compatible with @n@?
405\end{itemize}
406This compatibility question applies to a pair of expressions, where the earlier ones were to types.
407Such an expression-compatibility question is a new addition to the \CFA compiler.
408These questions only arise in the context of dimension expressions on (C) array types.
409
410TODO: ensure these compiler implementation matters are treated under \CFA compiler background:
411type unification,
412cost calculation,
413GenPoly.
414
415The relevant technical component of the \CFA compiler is,
416within the type resolver, the type unification procedure.
417I added rules for continuing this unification into expressions that occur within types.
418It is still fundamentally doing \emph{type} unification
419because it is participating in binding type variables,
420and not participating in binding any variables that stand in for expression fragments
421(for there is no such sort of variable in \CFA's analysis.)
422
423An unfortunate fact about the \CFA compiler's preexisting implementation is that
424type unification suffers from two forms of duplication.
425
426The first duplication has (many of) the unification rules stated twice.
427As a result, my additions for dimension expressions are stated twice.
428The extra statement of the rules occurs in the GenPoly module,
429where concrete types like @array(int, 5)@\footnote{
430        Again, the presentation is simplified
431        by leaving the \lstinline{array} macro unexpanded}
432are lowered into corresponding C types @struct __conc_array_1234@ (the suffix being a generated index).
433In this case, the struct's definition gives fields that hardcode the argument values of @float@ and @5@.
434The next time an @array(-,-)@ concrete instance is encountered,
435is the previous @struct __conc_array_1234@ suitable for it?
436Yes, for another occurrance of @array(int, 5)@;
437no, for either @array(rational(int), 5)@ or @array(int, 42)@.
438By the last example, this phase must ``reject''
439the hypothesis that it should reuse the dimension-5 instance's C-lowering for a dimension-42 instance.
440
441The second duplication has unification (proper) being invoked at two stages of expression resolution.
442As a result, my added rule set needs to handle more cases than the preceding discussion motivates.
443In the program
444\begin{cfa}
445        void f( double );
446        forall( T & ) void f( T & );
447        void g( int n ) {
448                array( float, n + 1 ) x;
449                f(x);
450        }
451\end{cfa}
452when resolving the function call, the first unification stage
453compares the types @T@, of the parameter, with @array( float, n + 1 )@, of the argument.
454TODO: finish.
455
456The actual rules for comparing two dimension expressions are conservative.
457To answer, ``yes, consider this pair of expressions to be matching,''
458is to imply, ``all else being equal, allow an array with length calculated by $e_1$
459to be passed to a function expecting a length-$e_2$ array.''\footnote{
460        TODO: Deal with directionality, that I'm doing exact-match, no ``at least as long as,'' no subtyping.
461        Should it be an earlier scoping principle?  Feels like it should matter in more places than here.}
462So, a ``yes'' answer must represent a guarantee that both expressions will evaluate the
463same result, while a ``no'' can tolerate ``they might, but we're not sure,'
464provided that practical recourses are available
465to let programmers express their better knowledge.
466The specific rule-set that I offer with the current release is, in fact, extremely conservative.
467I chose to keep things simple,
468and allow real future needs do drive adding additional complexity,
469within the framework that I laid out.
470
471For starters, the original motivating example's rejection
472is not based on knowledge that
473the @xp@ length of (the literal) 999 is value-unequal to
474the (obvious) runtime value of the variable @n@, which is the @x@ length.
475Rather, the analysis assumes a variable's value can be anything,
476and so there can be no guarantee that its value is 999.
477So, a variable use and a literal can never match.
478
479Two occurrences of the same literal value are obviously a fine match.
480For two occurrences of the same varialbe, more information is needed.
481For example, this one is fine
482\begin{cfa}
483        void f( const int n ) {
484                float x[n];
485                float (*xp)[n] = x; // accept
486        }
487\end{cfa}
488while this one is not:
489\begin{cfa}
490        void f() {
491                int n = 42;
492                float x[n];
493                n = 999;
494                float (*xp)[n] = x; // reject
495        }
496\end{cfa}
497Furthermore, the fact that the first example sees @n@ as @const@
498is not actually a sufficent basis.
499In this example, @f@'s length expression's declaration is as @const@ as it can be,
500yet its value still changes between the two invocations:
501\begin{cfa}
502        // compile unit 1
503        void g();
504        void f( const int & const nr ) {
505                float x[nr];
506                g();
507                float (*xp)[nr] = x; // reject
508        }
509        // compile unit 2
510        static int n = 42;
511        void g() {
512                n = 99;
513        }
514        void f( const int & );
515        int main () {
516                f(n);
517                return 0;
518        }
519\end{cfa}
520The issue in this last case is,
521just because you aren't able to change something doesn't mean someone else can't.
522
523My rule set also respects a feature of the C tradition.
524In spite of the several limitations of the C rules
525accepting cases that produce different values, there are a few mismatches that C stops.
526C is quite precise when working with two static values:
527\begin{cfa}
528        enum { fortytwo = 42 };
529        float x[fortytwo];
530        float (*xp1)[42] = &x; // accept
531        float (*xp2)[999] = &x; // reject
532\end{cfa}
533My \CFA rules agree with C's on these cases.
534
535My rules classify expressions into three groups:
536\begin{description}
537\item[Statically Evaluable]
538        Expressions for which a specific value can be calculated (conservatively)
539        at compile-time.
540        A preexisting \CFA compiler module defines which expressions qualify,
541        and evaluates them.
542        Includes literals and enumeration values.
543\item[Dynamic but Stable]
544        The value of a variable declared as @const@.
545        Includes a @const@ parameter.
546\item[Potentially Unstable]
547        The catch-all category.  Notable examples include:
548        any function-call result (@float x[foo()];@),
549        the particular function-call result that is a pointer dereference (@void f(const int * n) { float x[*n]; }@), and
550        any use of a reference-typed variable.
551\end{description}
552
553My \CFA rules are:
554\begin{itemize}
555\item
556        Accept a Statically Evaluable pair, if both expressions have the same value.
557        Notably, this rule allows a literal to match with an enumeration value, based on the value.
558\item
559        Accept a Dynamic but Stable pair, if both expressions are written out the same, e.g. refers to same variable declaration.
560\item
561        Otherwise, reject.
562        Notably, reject all pairs from the Potentially Unstable group.
563        Notably, reject all pairs that cross groups.
564\end{itemize}
565
566The traditional C rules are:
567\begin{itemize}
568\item
569        Reject a Statically Evaluable pair, if the expressions have two different values.
570\item
571        Otherwise, accept.
572\end{itemize}
573
574
575\newcommand{\falsealarm}{{\color{orange}\small{*}}}
576\newcommand{\allowmisuse}{{\color{red}\textbf{!}}}
577\newcommand{\cmark}{\ding{51}} % from pifont
578\newcommand{\xmark}{\ding{55}}
579\begin{figure}
580        \begin{tabular}{@{}l@{\hspace{16pt}}c@{\hspace{8pt}}c@{\hspace{16pt}}c@{\hspace{8pt}}c@{\hspace{16pt}}c}
581         & \multicolumn{2}{c}{\underline{Values Equal}}
582         & \multicolumn{2}{c}{\underline{Values Unequal}} 
583         & \\
584        \textbf{Case}                                & C      & \CFA                & C                      & \CFA    & Compat. \\
585        Both Statically Evaluable, Same Symbol       & Accept & Accept              &                        &         & \cmark \\
586        Both Statically Evaluable, Different Symbols & Accept & Accept              & Reject                 & Reject  & \cmark \\
587        Both Dynamic but Stable, Same Symbol         & Accept & Accept              &                        &         & \cmark \\
588        Both Dynamic but Stable, Different Symbols   & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark \\
589        Both Potentially Unstable, Same Symbol       & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark \\
590        Any other grouping, Different Symbol         & Accept & Reject\,\falsealarm & Accept\,\allowmisuse   & Reject  & \xmark
591        \end{tabular}
592
593        \vspace{12pt}
594        \noindent\textbf{Legend:}
595        \begin{itemize}
596        \item
597                Each row gives the treatment of a test harness of the form
598                \begin{cfa}
599                        float x[ expr1 ];
600                        float (*xp)[ expr2 ] = &x;
601                \end{cfa}
602                where \lstinline{expr1} and \lstinline{expr2} are metavariables varying according to the row's Case.
603                Each row's claim applies to other harnesses too, including,
604                \begin{itemize}
605                \item
606                        calling a function with a paramter like \lstinline{x} and an argument of the \lstinline{xp} type,
607                \item
608                        assignment in place of initialization,
609                \item
610                        using references in place of pointers, and
611                \item
612                        for the \CFA array, calling a polymorphic function on two \lstinline{T}-typed parameters with \lstinline{&x}- and \lstinline{xp}-typed arguments.
613                \end{itemize}
614        \item
615                Each case's claim is symmetric (swapping \lstinline{expr1} with \lstinline{expr2} has no effect),
616                even though most test harnesses are asymetric.
617        \item
618                The table treats symbolic identity (Same/Different on rows)
619                apart from value eqality (Equal/Unequal on columns).
620                \begin{itemize}
621                \item
622                        The expressions \lstinline{1}, \lstinline{0+1} and \lstinline{n}
623                        (where \lstinline{n} is a variable with value 1),
624                        are all different symbols with the value 1.
625                \item
626                        The column distinction expresses ground truth about whether an omniscient analysis should accept or reject.
627                \item
628                        The row distinction expresses the simple static factors used by today's analyses.
629                \end{itemize}
630        \item
631                Accordingly, every Reject under Values Equal is a false alarm (\falsealarm),
632                while every Accept under Values Unequal is an allowed misuse (\allowmisuse).
633        \end{itemize}
634        \caption{Case comparison for array type compatibility, given pairs of dimension expressions.
635                TODO: get Peter's LaTeX help on overall appearance, probably including column spacing/centering and bullet indentation.}
636        \label{f:DimexprRuleCompare}
637\end{figure}
638
639
640Figure~\ref{f:DimexprRuleCompare} gives a case-by-case comparison of the consequences of these rule sets.
641It demonstrates that the \CFA false alarms occur in the same cases as C treats unsafely.
642It also shows that C-incompatibilities only occur in cases that C treats unsafely.
643
644
645The conservatism of the new rule set can leave a programmer needing a recourse,
646when needing to use a dimension expression whose stability argument
647is more subtle than current-state analysis.
648This recourse is to declare an explicit constant for the dimension value.
649Consider these two dimension expressions,
650whose reuses are rejected by the blunt current-state rules:
651\begin{cfa}
652        void f( int & nr, const int nv ) {
653                float x[nr];
654                float (*xp)[nr] = & x; // reject: nr varying (no references)
655                float y[nv + 1];
656                float (*yp)[nv + 1] = & y; // reject: ?+? unpredicable (no functions)
657        }
658\end{cfa}
659Yet, both dimension expressions are reused safely.
660(The @nr@ reference is never written, not volatile
661and control does not leave the function between the uses.
662The name @?+?@ resolves to a function that is quite predictable.)
663The programmer here can add the constant declarations:
664\begin{cfa}
665        void f( int & nr, const int nv ) {
666                @const int nx@ = nr;
667                float x[nx];
668                float (*xp)[nx] = & x; // acept
669                @const int ny@ = nv + 1;
670                float y[ny];
671                float (*yp)[ny] = & y; // accept
672        }
673\end{cfa}
674The result is the originally intended semantics,
675achieved by adding a superfluous ``snapshot it as of now'' directive.
676
677The snapshotting trick is also used by the translation, though to achieve a different outcome.
678Rather obviously, every array must be subscriptable, even a bizzarre one:
679\begin{cfa}
680        array( float, rand(10) ) x;
681        x[0];  // 10% chance of bound-check failure
682\end{cfa}
683Less obvious is that the mechanism of subscripting is a function call,
684which must communicate length accurately.
685The bound-check above (callee logic) must use the actual allocated length of @x@,
686without mistakenly reevaluating the dimension expression, @rand(10)@.
687Adjusting the example to make the function's use of length more explicit:
688\begin{cfa}
689        forall ( T * )
690        void f( T * x ) { sout | sizeof(*x); }
691        float x[ rand(10) ];
692        f( x );
693\end{cfa}
694Considering that the partly translated function declaration is, loosely,
695\begin{cfa}
696        void f( size_t __sizeof_T, void * x ) { sout | __sizeof_T; }
697\end{cfa}
698the translated call must not go like:
699\begin{cfa}
700        float x[ rand(10) ];
701        f( rand(10), &x );
702\end{cfa}
703Rather, its actual translation is like:
704\begin{cfa}
705        size_t __dim_x = rand(10);
706        float x[ __dim_x ];
707        f( __dim_x, &x );
708\end{cfa}
709The occurrence of this dimension hoisting during translation was present in the preexisting \CFA compiler.
710But its cases were buggy, particularly with determining, ``Can hoisting be skipped here?''
711For skipping this hoisting is clearly desirable in some cases,
712not the least of which is when the programmer has already done so manually.
713My work includes getting these cases right, harmonized with the accept/reject criteria, and tested.
714
715
716
717TODO: Discuss the interaction of this dimension hoisting with the challenge of extra unification for cost calculation
718
719\section{Multidimensional Arrays}
720\label{toc:mdimpl}
721
722% TODO: introduce multidimensional array feature and approaches
723
724When working with arrays, \eg linear algebra, array dimensions are referred to as ``rows'' and ``columns'' for a matrix, adding ``planes'' for a cube.
725(There is little terminology for higher dimensional arrays.)
726For 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.}
727can be treated as a grid of characters, where the rows are the text and the columns are the embedded keyword(s).
728Within 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.
729In general, the dimensioning and subscripting for multidimensional arrays has two syntactic forms: @m[r,c]@ or @m[r][c]@.
730
731Commonly, an array, matrix, or cube, is visualized (especially in mathematics) as a contiguous row, rectangle, or block.
732This conceptualization is reenforced by subscript ordering, \eg $m_{r,c}$ for a matrix and $c_{p,r,c}$ for a cube.
733Few programming languages differ from the mathematical subscript ordering.
734However, computer memory is flat, and hence, array forms are structured in memory as appropriate for the runtime system.
735The 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.
736This 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.
737For 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.
738In general, storage layout is hidden by subscripting, and only appears when passing arrays among different programming languages or accessing specific hardware.
739
740\VRef[Figure]{f:FixedVariable} shows two C90 approaches for manipulating a contiguous matrix.
741Note, C90 does not support VLAs.
742The fixed-dimension approach (left) uses the type system;
743however, 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.
744Hence, every matrix passed to @fp1@ must have exactly 6 columns but the row size can vary.
745The 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@.
746
747\begin{figure}
748\begin{tabular}{@{}l@{\hspace{40pt}}l@{}}
749\multicolumn{1}{c}{\textbf{Fixed Dimension}} & \multicolumn{1}{c}{\textbf{Variable Dimension}} \\
750\begin{cfa}
751
752void fp1( int rows, int m[][@6@] ) {
753        ...  printf( "%d ", @m[r][c]@ );  ...
754}
755int fm1[4][@6@], fm2[6][@6@]; // no VLA
756// initialize matrixes
757fp1( 4, fm1 ); // implicit 6 columns
758fp1( 6, fm2 );
759\end{cfa}
760&
761\begin{cfa}
762#define sub( m, r, c ) *(m + r * sizeof( m[0] ) + c)
763void fp2( int rows, int cols, int *m ) {
764        ...  printf( "%d ", @sub( m, r, c )@ );  ...
765}
766int vm1[@4@][@4@], vm2[@6@][@8@]; // no VLA
767// initialize matrixes
768fp2( 4, 4, vm1 );
769fp2( 6, 8, vm2 );
770\end{cfa}
771\end{tabular}
772\caption{C90 Fixed \vs Variable Contiguous Matrix Styles}
773\label{f:FixedVariable}
774\end{figure}
775
776Many languages allow multidimensional arrays-of-arrays, \eg in Pascal or \CC.
777\begin{cquote}
778\begin{tabular}{@{}ll@{}}
779\begin{pascal}
780var m : array[0..4, 0..4] of Integer;  (* matrix *)
781type AT = array[0..4] of Integer;  (* array type *)
782type MT = array[0..4] of AT;  (* array of array type *)
783var aa : MT;  (* array of array variable *)
784m@[1][2]@ := 1;   aa@[1][2]@ := 1 (* same subscripting *)
785\end{pascal}
786&
787\begin{c++}
788int m[5][5];
789
790typedef vector< vector<int> > MT;
791MT vm( 5, vector<int>( 5 ) );
792m@[1][2]@ = 1;  aa@[1][2]@ = 1;
793\end{c++}
794\end{tabular}
795\end{cquote}
796The language decides if the matrix and array-of-array are laid out the same or differently.
797For 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).
798Regardless, 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]@.
799Nevertheless, controlling memory layout can make a difference in what operations are allowed and in performance (caching/NUMA effects).
800
801C also provides non-contiguous arrays-of-arrays.
802\begin{cfa}
803int m[5][5];                                                    $\C{// contiguous}$
804int * aa[5];                                                    $\C{// non-contiguous}$
805\end{cfa}
806both with different memory layout using the same subscripting, and both with different degrees of issues.
807The focus of this work is on the contiguous multidimensional arrays in C.
808The 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.
809Nevertheless, the C array-of-array form is still important for special circumstances.
810
811\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.}
812First, VLAs are supported.
813Second, 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@.
814If the declaration of @fc@ is changed to:
815\begin{cfa}
816void fc( int rows, int cols, int m[@rows@][@cols@] ) ...
817\end{cfa}
818it is possible for C to perform bound checking across all subscripting, but it does not.
819While 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.
820That is, the array does not automatically carry its structure and sizes for use in computing subscripts.
821While 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.
822Specifically, there is no requirement that the rows are the same length, like a poem with different length lines.
823
824\begin{figure}
825\begin{tabular}{@{}ll@{}}
826\multicolumn{1}{c}{\textbf{Contiguous}} & \multicolumn{1}{c}{\textbf{ Non-contiguous}} \\
827\begin{cfa}
828void fc( int rows, @int cols@, int m[ /* rows */ ][@cols@] ) {
829        ...  printf( "%d ", @m[r][c]@ );  ...
830}
831int m@[5][5]@;
832for ( int r = 0; r < 5; r += 1 ) {
833
834        for ( int c = 0; c < 5; c += 1 )
835                m[r][c] = r + c;
836}
837fc( 5, 5, m );
838\end{cfa}
839&
840\begin{cfa}
841void faa( int rows, int cols, int * m[ @/* cols */@ ] ) {
842        ...  printf( "%d ", @m[r][c]@ );  ...
843}
844int @* aa[5]@;  // row pointers
845for ( int r = 0; r < 5; r += 1 ) {
846        @aa[r] = malloc( 5 * sizeof(int) );@ // create rows
847        for ( int c = 0; c < 5; c += 1 )
848                aa[r][c] = r + c;
849}
850faa( 5, 5, aa );
851\end{cfa}
852\end{tabular}
853\caption{C99 Contiguous \vs Non-contiguous Matrix Styles}
854\label{f:ContiguousNon-contiguous}
855\end{figure}
856
857
858\subsection{Multidimensional array implementation}
859
860A multidimensional array implementation has three relevant levels of abstraction, from highest to lowest, where the array occupies \emph{contiguous memory}.
861\begin{enumerate}
862\item
863Flexible-stride memory:
864this 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]@.
865\item
866Fixed-stride memory:
867this 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).
868After which, subscripting and memory layout are independent.
869\item
870Explicit-displacement memory:
871this 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@.
872A programmer must manually build any notion of dimensions using other tools;
873hence, this style is not offering multidimensional arrays \see{\VRef[Figure]{f:FixedVariable} right example}.
874\end{enumerate}
875
876There is some debate as to whether the abstraction ordering goes $\{1, 2\} < 3$, rather than my numerically-ordering.
877That is, styles 1 and 2 are at the same abstraction level, with 3 offering a limited set of functionality.
878I chose to build the \CFA style-1 array upon a style-2 abstraction.
879(Justification of the decision follows, after the description of the design.)
880
881Style 3 is the inevitable target of any array implementation.
882The hardware offers this model to the C compiler, with bytes as the unit of displacement.
883C offers this model to its programmer as pointer arithmetic, with arbitrary sizes as the unit.
884Casting 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.
885
886Now 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.
887A C/\CFA array interface includes the resulting memory layout.
888The defining requirement of a type-2 system is the ability to slice a column from a column-finest matrix.
889The required memory shape of such a slice is fixed, before any discussion of implementation.
890The 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.
891TODO: do I have/need a presentation of just this layout, just the semantics of -[all]?
892
893The new \CFA standard library @array@ datatype supports richer multidimensional features than C.
894The 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.
895Beyond 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.
896
897The 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.
898\par
899\mbox{\lstinput{121-126}{hello-md.cfa}}
900\par\noindent
901The memory layout is 35 contiguous elements with strictly increasing addresses.
902
903A trivial form of slicing extracts a contiguous inner array, within an array-of-arrays.
904As 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.
905This 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@.
906The following is an example slicing a row.
907\lstinput{60-64}{hello-md.cfa}
908\lstinput[aboveskip=0pt]{140-140}{hello-md.cfa}
909
910However, function @print1d@ is asserting too much knowledge about its parameter @r@ for printing either a row slice or a column slice.
911Specifically, declaring the parameter @r@ with type @array@ means that @r@ is contiguous, which is unnecessarily restrictive.
912That is, @r@ need only be of a container type that offers a subscript operator (of type @ptrdiff_t@ $\rightarrow$ @float@) with managed length @N@.
913The new-array library provides the trait @ar@, so-defined.
914With it, the original declaration can be generalized with the same body.
915\lstinput{43-44}{hello-md.cfa}
916\lstinput[aboveskip=0pt]{145-145}{hello-md.cfa}
917The 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.
918In 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.
919\lstinput{150-151}{hello-md.cfa}
920
921The example shows @x[2]@ and @x[[2, all]]@ both refer to the same, ``2.*'' slice.
922Indeed, 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]@.
923This 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''.
924That is:
925\begin{cquote}
926\begin{tabular}{@{}cccccl@{}}
927@x[[2,all]][3]@ & $\equiv$      & @x[2][all][3]@  & $\equiv$    & @x[2][3]@  & (here, @all@ is redundant)  \\
928@x[[all,3]][2]@ & $\equiv$      & @x[all][3][2]@  & $\equiv$    & @x[2][3]@  & (here, @all@ is effective)
929\end{tabular}
930\end{cquote}
931
932Narrating progress through each of the @-[-][-][-]@\footnote{
933The first ``\lstinline{-}'' is a variable expression and the remaining ``\lstinline{-}'' are subscript expressions.}
934expressions gives, firstly, a definition of @-[all]@, and secondly, a generalization of C's @-[i]@.
935Where @all@ is redundant:
936\begin{cquote}
937\begin{tabular}{@{}ll@{}}
938@x@  & 2-dimensional, want subscripts for coarse then fine \\
939@x[2]@  & 1-dimensional, want subscript for fine; lock coarse == 2 \\
940@x[2][all]@  & 1-dimensional, want subscript for fine \\
941@x[2][all][3]@  & 0-dimensional; lock fine == 3
942\end{tabular}
943\end{cquote}
944Where @all@ is effective:
945\begin{cquote}
946\begin{tabular}{@{}ll@{}}
947@x@  & 2-dimensional, want subscripts for coarse then fine \\
948@x[all]@  & 2-dimensional, want subscripts for fine then coarse \\
949@x[all][3]@  & 1-dimensional, want subscript for coarse; lock fine == 3 \\
950@x[all][3][2]@  & 0-dimensional; lock coarse == 2
951\end{tabular}
952\end{cquote}
953The semantics of @-[all]@ is to dequeue from the front of the ``want subscripts'' list and re-enqueue at its back.
954For example, in a two dimensional matrix, this semantics conceptually transposes the matrix by reversing the subscripts.
955The semantics of @-[i]@ is to dequeue from the front of the ``want subscripts'' list and lock its value to be @i@.
956
957Contiguous arrays, and slices of them, are all represented by the same underlying parameterized type, which includes stride information in its metatdata.
958\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.}
959The running example's @all@-effective step, stated more concretely, is:
960\begin{cquote}
961\begin{tabular}{@{}ll@{}}
962@x@       & : 5 of ( 7 of @float@ each spaced 1 @float@ apart ) each spaced 7 @floats@ apart \\
963@x[all]@  & : 7 of ( 5 of @float@ each spaced 7 @float@s apart ) each spaced 1 @float@ apart
964\end{tabular}
965\end{cquote}
966
967\begin{figure}
968\includegraphics{measuring-like-layout}
969\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.
970The horizontal layout represents contiguous memory addresses while the vertical layout is conceptual.
971The vertical shaded band highlights the location of the targeted element, 2.3.
972Any such vertical slice contains various interpretations of a single address.}
973\label{fig:subscr-all}
974\end{figure}
975
976Figure~\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]@.
977In both cases, value 2 selects from the coarser dimension (rows of @x@),
978while the value 3 selects from the finer dimension (columns of @x@).
979The figure illustrates the value of each subexpression, comparing how numeric subscripting proceeds from @x@, \vs from @x[all]@.
980Proceeding from @x@ gives the numeric indices as coarse then fine, while proceeding from @x[all]@ gives them fine then coarse.
981These two starting expressions, which are the example's only multidimensional subexpressions
982(those that received zero numeric indices so far), are illustrated with vertical steps where a \emph{first} numeric index would select.
983
984The figure's presentation offers an intuition answering to: What is an atomic element of @x[all]@?
985From there, @x[all]@ itself is simply a two-dimensional array, in the strict C sense, of these building blocks.
986An atom (like the bottommost value, @x[all][3][2]@), is the contained value (in the square box)
987and a lie about its size (the left diagonal above it, growing upward).
988An array of these atoms (like the intermediate @x[all][3]@) is just a contiguous arrangement of them, done according to their size;
989call such an array a column.
990A column is almost ready to be arranged into a matrix;
991it is the \emph{contained value} of the next-level building block, but another lie about size is required.
992At 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).
993These lying columns, arranged contiguously according to their size (as announced) form the matrix @x[all]@.
994Because @x[all]@ takes indices, first for the fine stride, then for the coarse stride, it achieves the requirement of representing the transpose of @x@.
995Yet every time the programmer presents an index, a C-array subscript is achieving the offset calculation.
996
997In the @x[all]@ case, after the finely strided subscript is done (column 3 is selected),
998the locations referenced by the coarse subscript options (rows 0..4) are offset by 3 floats,
999compared with where analogous rows appear when the row-level option is presented for @x@.
1000
1001For 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).
1002But only the atom 2.3 is storing its value there.
1003The rest are lying about (conflicting) claims on this location, but never exercising these alleged claims.
1004
1005Lying is implemented as casting.
1006The arrangement just described is implemented in the structure @arpk@.
1007This structure uses one type in its internal field declaration and offers a different type as the return of its subscript operator.
1008The 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]@.
1009The subscript operator presents what is really inside, by casting to the type below the left diagonal of the lie.
1010
1011%  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.
1012
1013Casting, overlapping, and lying are unsafe.
1014The mission is to implement a style-1 feature in the type system for safe use by a programmer.
1015The offered style-1 system is allowed to be internally unsafe,
1016just 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.
1017Having a style-1 system relieves the programmer from resorting to unsafe pointer arithmetic when working with noncontiguous slices.
1018
1019% PAB: repeat from previous paragraph.
1020% 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.
1021% My casting is unsafe, but I do not do any pointer arithmetic.
1022% 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.
1023% 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.
1024
1025% \noindent END: Paste looking for a home
1026
1027The new-array library defines types and operations that ensure proper elements are accessed soundly in spite of the overlapping.
1028The @arpk@ structure and its @-[i]@ operator are defined as:
1029\begin{cfa}
1030forall(
1031        [N],                                    $\C{// length of current dimension}$
1032        S & | sized(S),                 $\C{// masquerading-as}$
1033        Timmed &,                               $\C{// immediate element, often another array}$
1034        Tbase &                                 $\C{// base element, e.g. float, never array}$
1035) { // distribute forall to each element
1036        struct arpk {
1037                S strides[N];           $\C{// so that sizeof(this) is N of S}$
1038        };
1039        // expose Timmed, stride by S
1040        static inline Timmed & ?[?]( arpk( N, S, Timmed, Tbase ) & a, long int i ) {
1041                subcheck( a, i, 0, N );
1042                return (Timmed &)a.strides[i];
1043        }
1044}
1045\end{cfa}
1046The private @arpk@ structure (array with explicit packing) is generic over four types: dimension length, masquerading-as, ...
1047This structure's public interface is hidden behind the @array(...)@ macro and the subscript operator.
1048Construction by @array@ initializes the masquerading-as type information to be equal to the contained-element information.
1049Subscripting by @all@ rearranges the order of masquerading-as types to achieve, in general, nontrivial striding.
1050Subscripting 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.
1051
1052An 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, ...)@.
1053In the base case, @array(E_base)@ is just @E_base@.
1054Because this construction uses the same value for the generic parameters @S@ and @E_im@, the resulting layout has trivial strides.
1055
1056Subscripting 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.
1057Expressed as an operation on types, this rotation is:
1058\begin{eqnarray*}
1059suball( arpk(N, S, E_i, E_b) ) & = & enq( N, S, E_i, E_b ) \\
1060enq( N, S, E_b, E_b ) & = & arpk( N, S, E_b, E_b ) \\
1061enq( N, S, arpk(N', S', E_i', E_b), E_b ) & = & arpk( N', S', enq(N, S, E_i', E_b), E_b )
1062\end{eqnarray*}
1063
1064
1065\section{Bound checks, added and removed}
1066
1067\CFA array subscripting is protected with runtime bound checks.
1068Having dependent typing causes the optimizer to remove more of these bound checks than it would without them.
1069This section provides a demonstration of the effect.
1070
1071The 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.
1072The 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.
1073The experiment compares with the \CC version to keep access to generated assembly code simple.
1074
1075As 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.
1076When 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.
1077But 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.
1078
1079TODO: paste source and assembly codes
1080
1081Incorporating reuse among dimension sizes is seen to give \CFA an advantage at being optimized.
1082The case is naive matrix multiplication over a row-major encoding.
1083
1084TODO: paste source codes
1085
1086
1087
1088
1089
1090\section{Comparison with other arrays}
1091
1092
1093\subsection{Rust}
1094
1095\CFA's array is the first lightweight application of dependently-typed bound tracking to an extension of C.
1096Other 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.
1097These systems, therefore, ask the programmer to convince the type checker that every pointer dereference is valid.
1098\CFA imposes the lighter-weight obligation, with the more limited guarantee, that initially-declared bounds are respected thereafter.
1099
1100\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.
1101Other 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.
1102The \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.
1103
1104
1105\subsection{Java}
1106
1107Java arrays are arrays-of-arrays because all objects are references \see{\VRef{toc:mdimpl}}.
1108For each array, Java implicitly storages the array dimension in a descriptor, supporting array length, subscript checking, and allowing dynamically-sized array-parameter declarations.
1109\begin{cquote}
1110\begin{tabular}{rl}
1111C      &  @void f( size_t n, size_t m, float x[n][m] );@ \\
1112Java   &  @void f( float x[][] );@
1113\end{tabular}
1114\end{cquote}
1115However, in the C prototype, the parameters @n@ and @m@  are documentation only as the intended size of the first and second dimension of @x@.
1116\VRef[Figure]{f:JavaVsCTriangularMatrix} compares a triangular matrix (array-of-arrays) in dynamically safe Java to unsafe C.
1117Each dynamically sized row in Java stores its dimension, while C requires the programmer to manage these sizes explicitly (@rlnth@).
1118All subscripting is Java has bounds checking, while C has none.
1119Both Java and C require explicit null checking, otherwise there is a runtime failure.
1120
1121\begin{figure}
1122\setlength{\tabcolsep}{15pt}
1123\begin{tabular}{ll@{}}
1124\begin{java}
1125int m[][] = {  // triangular matrix
1126        new int [4],
1127        new int [3],
1128        new int [2],
1129        new int [1],
1130        null
1131};
1132
1133for ( int r = 0; r < m.length; r += 1 ) {
1134        if ( m[r] == null ) continue;
1135        for ( int c = 0; c < m[r].length; c += 1 ) {
1136                m[r][c] = c + r; // subscript checking
1137        }
1138
1139}
1140
1141for ( int r = 0; r < m.length; r += 1 ) {
1142        if ( m[r] == null ) {
1143                System.out.println( "null row" );
1144                continue;
1145        }
1146        for ( int c = 0; c < m[r].length; c += 1 ) {
1147                System.out.print( m[r][c] + " " );
1148        }
1149        System.out.println();
1150
1151}
1152\end{java}
1153&
1154\begin{cfa}
1155int * m[5] = {  // triangular matrix
1156        calloc( 4, sizeof(int) ),
1157        calloc( 3, sizeof(int) ),
1158        calloc( 2, sizeof(int) ),
1159        calloc( 1, sizeof(int) ),
1160        NULL
1161};
1162int rlnth = 4;
1163for ( int r = 0; r < 5; r += 1 ) {
1164        if ( m[r] == NULL ) continue;
1165        for ( int c = 0; c < rlnth; c += 1 ) {
1166                m[r][c] = c + r; // no subscript checking
1167        }
1168        rlnth -= 1;
1169}
1170rlnth = 4;
1171for ( int r = 0; r < 5; r += 1 ) {
1172        if ( m[r] == NULL ) {
1173                printf( "null row\n" );
1174                continue;
1175        }
1176        for ( int c = 0; c < rlnth; c += 1 ) {
1177                printf( "%d ", m[r][c] );
1178        }
1179        printf( "\n" );
1180        rlnth -= 1;
1181}
1182\end{cfa}
1183\end{tabular}
1184\caption{Java (left) \vs C (right) Triangular Matrix}
1185\label{f:JavaVsCTriangularMatrix}
1186\end{figure}
1187
1188The downside of the arrays-of-arrays approach is performance due to pointer chasing versus pointer arithmetic for a contiguous arrays.
1189Furthermore, there is the cost of managing the implicit array descriptor.
1190It is unlikely that a JIT can dynamically rewrite an arrays-of-arrays form into a contiguous form.
1191
1192
1193\subsection{\CC}
1194
1195Because C arrays are difficult and dangerous, the mantra for \CC programmers is to use @std::vector@ in place of the C array.
1196While 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@.
1197\begin{c++}
1198vector< vector< int > > m( 5, vector<int>(8) ); // initialize size of 5 x 8 with 6 dynamic allocations
1199\end{c++}
1200Multidimensional arrays are arrays-of-arrays with associated costs.
1201Each @vector@ array has an array descriptor contain the dimension, which allows bound checked using @x.at(i)@ in place of @x[i]@.
1202Used 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.
1203This scheme matches Java's safety and expressiveness exactly, but with the inherent costs.
1204
1205
1206\subsection{Levels of dependently typed arrays}
1207
1208The \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:
1209\begin{itemize}
1210\item a \emph{zip}-style operation that consumes two arrays of equal length
1211\item a \emph{map}-style operation whose produced length matches the consumed length
1212\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
1213\end{itemize}
1214Across 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.
1215Along the way, the \CFA array also closes the safety gap (with respect to bounds) that Java has over C.
1216
1217Dependent type systems, considered for the purpose of bound-tracking, can be full-strength or restricted.
1218In a full-strength dependent type system, a type can encode an arbitrarily complex predicate, with bound-tracking being an easy example.
1219The tradeoff of this expressiveness is complexity in the checker, even typically, a potential for its nontermination.
1220In 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.
1221[TODO: clarify how even Idris type checking terminates]
1222
1223Idris is a current, general-purpose dependently typed programming language.
1224Length checking is a common benchmark for full dependent type systems.
1225Here, 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.
1226[TODO: finish explaining what Data.Vect is and then the essence of the comparison]
1227
1228POINTS:
1229here is how our basic checks look (on a system that does not have to compromise);
1230it can also do these other cool checks, but watch how I can mess with its conservativeness and termination
1231
1232Two 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.
1233Unlike \CFA, both are garbage-collected functional languages.
1234Because they are garbage-collected, referential integrity is built-in, meaning that the heavyweight analysis, that \CFA aims to avoid, is unnecessary.
1235So, like \CFA, the checking in question is a lightweight bounds-only analysis.
1236Like \CFA, their checks that are conservatively limited by forbidding arithmetic in the depended-upon expression.
1237
1238
1239
1240The 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.
1241There is a particular emphasis on an existential type, enabling callee-determined return shapes.
1242
1243
1244Dex uses a novel conception of size, embedding its quantitative information completely into an ordinary type.
1245
1246Futhark and full-strength dependently typed languages treat array sizes are ordinary values.
1247Futhark restricts these expressions syntactically to variables and constants, while a full-strength dependent system does not.
1248
1249\CFA's hybrid presentation, @forall( [N] )@, has @N@ belonging to the type system, yet has no instances.
1250Belonging to the type system means it is inferred at a call site and communicated implicitly, like in Dex and unlike in Futhark.
1251Having 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.
1252
1253\subsection{Static safety in C extensions}
1254
1255
1256\section{Future work}
1257
1258\subsection{Declaration syntax}
1259
1260\subsection{Range slicing}
1261
1262\subsection{With a module system}
1263
1264\subsection{With described enumerations}
1265
1266A project in \CFA's current portfolio will improve enumerations.
1267In the incumbent state, \CFA has C's enumerations, unmodified.
1268I 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.
1269It also has a candidate stretch goal, to adapt \CFA's @forall@ generic system to communicate generalized enumerations:
1270\begin{cfa}
1271forall( T | is_enum(T) )
1272void show_in_context( T val ) {
1273        for( T i ) {
1274                string decorator = "";
1275                if ( i == val-1 ) decorator = "< ready";
1276                if ( i == val   ) decorator = "< go"   ;
1277                sout | i | decorator;
1278        }
1279}
1280enum weekday { mon, tue, wed = 500, thu, fri };
1281show_in_context( wed );
1282\end{cfa}
1283with output
1284\begin{cfa}
1285mon
1286tue < ready
1287wed < go
1288thu
1289fri
1290\end{cfa}
1291The details in this presentation aren't meant to be taken too precisely as suggestions for how it should look in \CFA.
1292But the example shows these abilities:
1293\begin{itemize}
1294\item a built-in way (the @is_enum@ trait) for a generic routine to require enumeration-like information about its instantiating type
1295\item an implicit implementation of the trait whenever a user-written enum occurs (@weekday@'s declaration implies @is_enum@)
1296\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@)
1297\item a provision for looping (the @for@ form used) over the values of the type.
1298\end{itemize}
1299
1300If \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.
1301
1302[TODO: introduce Ada in the comparators]
1303
1304In 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.
1305The 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.
1306
1307This change of perspective also lets us remove ubiquitous dynamic bound checks.
1308[TODO: xref] discusses how automatically inserted bound checks can often be optimized away.
1309But this approach is unsatisfying to a programmer who believes she has written code in which dynamic checks are unnecessary, but now seeks confirmation.
1310To 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.
1311
1312[TODO, fix confusion:  Idris has this arrangement of checks, but still the natural numbers as the domain.]
1313
1314The 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.
1315Dex's @Ix@ is analogous the @is_enum@ proposed for \CFA above.
1316\begin{cfa}
1317interface Ix n
1318get_size n : Unit -> Int
1319ordinal : n -> Int
1320unsafe_from_ordinal n : Int -> n
1321\end{cfa}
1322
1323Dex uses this foundation of a trait (as an array type's domain) to achieve polymorphism over shapes.
1324This 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.
1325Dex's example is a routine that calculates pointwise differences between two samples.
1326Done 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).
1327In 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.
1328
1329The polymorphism plays out with the pointwise-difference routine advertising a single-dimensional interface whose domain type is generic.
1330In the audio instantiation, the duration-of-clip type argument is used for the domain.
1331In the photograph instantiation, it's the tuple-type of $ \langle \mathrm{img\_wd}, \mathrm{img\_ht} \rangle $.
1332This 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
1333\begin{cfa}
1334instance {a b} [Ix a, Ix b] Ix (a & b)
1335get_size = \(). size a * size b
1336ordinal = \(i, j). (ordinal i * size b) + ordinal j
1337unsafe_from_ordinal = \o.
1338bs = size b
1339(unsafe_from_ordinal a (idiv o bs), unsafe_from_ordinal b (rem o bs))
1340\end{cfa}
1341and 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
1342\begin{cfa}
1343img_trans :: (img_wd,img_ht)=>Real
1344img_trans.(i,j) = img.i.j
1345result = pairwise img_trans
1346\end{cfa}
1347[TODO: cite as simplification of example from https://openreview.net/pdf?id=rJxd7vsWPS section 4]
1348
1349In 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.
1350
1351\subsection{Retire pointer arithmetic}
1352
1353
1354\section{\CFA}
1355
1356XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
1357moved from background chapter \\
1358XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\
1359
1360Traditionally, fixing C meant leaving the C-ism alone, while providing a better alternative beside it.
1361(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.)
1362
1363\subsection{\CFA features interacting with arrays}
1364
1365Prior work on \CFA included making C arrays, as used in C code from the wild,
1366work, if this code is fed into @cfacc@.
1367The quality of this this treatment was fine, with no more or fewer bugs than is typical.
1368
1369More mixed results arose with feeding these ``C'' arrays into preexisting \CFA features.
1370
1371A notable success was with the \CFA @alloc@ function,
1372which type information associated with a polymorphic return type
1373replaces @malloc@'s use of programmer-supplied size information.
1374\begin{cfa}
1375// C, library
1376void * malloc( size_t );
1377// C, user
1378struct tm * el1 = malloc( sizeof(struct tm) );
1379struct tm * ar1 = malloc( 10 * sizeof(struct tm) );
1380
1381// CFA, library
1382forall( T * ) T * alloc();
1383// CFA, user
1384tm * el2 = alloc();
1385tm (*ar2)[10] = alloc();
1386\end{cfa}
1387The alloc polymorphic return compiles into a hidden parameter, which receives a compiler-generated argument.
1388This compiler's argument generation uses type information from the left-hand side of the initialization to obtain the intended type.
1389Using a compiler-produced value eliminates an opportunity for user error.
1390
1391TODO: 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
1392
1393Bringing 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.
1394In the last example, the choice of ``pointer to array'' @ar2@ breaks a parallel with @ar1@.
1395They are not subscripted in the same way.
1396\begin{cfa}
1397ar1[5];
1398(*ar2)[5];
1399\end{cfa}
1400Using ``reference to array'' works at resolving this issue.  TODO: discuss connection with Doug-Lea \CC proposal.
1401\begin{cfa}
1402tm (&ar3)[10] = *alloc();
1403ar3[5];
1404\end{cfa}
1405The implicit size communication to @alloc@ still works in the same ways as for @ar2@.
1406
1407Using proper array types (@ar2@ and @ar3@) addresses a concern about using raw element pointers (@ar1@), albeit a theoretical one.
1408TODO xref C standard does not claim that @ar1@ may be subscripted,
1409because no stage of interpreting the construction of @ar1@ has it be that ``there is an \emph{array object} here.''
1410But both @*ar2@ and the referent of @ar3@ are the results of \emph{typed} @alloc@ calls,
1411where the type requested is an array, making the result, much more obviously, an array object.
1412
1413The ``reference to array'' type has its sore spots too.
1414TODO see also @dimexpr-match-c/REFPARAM_CALL@ (under @TRY_BUG_1@)
1415
1416TODO: 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.