source: doc/user/user.tex @ 07bc165

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since 07bc165 was 07bc165, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

update section on pointer/reference and LaTeX macros

  • Property mode set to 100644
File size: 200.2 KB
Line 
1%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%%
2%%
3%% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
4%%
5%% The contents of this file are covered under the licence agreement in the
6%% file "LICENCE" distributed with Cforall.
7%%
8%% user.tex --
9%%
10%% Author           : Peter A. Buhr
11%% Created On       : Wed Apr  6 14:53:29 2016
12%% Last Modified By : Peter A. Buhr
13%% Last Modified On : Sun Jul 10 12:52:09 2016
14%% Update Count     : 1200
15%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
16
17% requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended
18
19% inline code ©...© (copyright symbol) emacs: C-q M-)
20% red highlighting ®...® (registered trademark symbol) emacs: C-q M-.
21% blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_
22% green highlighting ¢...¢ (cent symbol) emacs: C-q M-"
23% LaTex escape §...§ (section symbol) emacs: C-q M-'
24% keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^
25% math escape $...$ (dollar symbol)
26
27\documentclass[twoside,11pt]{article}
28
29%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30
31% Latex packages used in the document.
32\usepackage[T1]{fontenc}                                % allow Latin1 (extended ASCII) characters
33\usepackage{textcomp}
34\usepackage[latin1]{inputenc}
35\usepackage{fullpage,times,comment}
36\usepackage{epic,eepic}
37\usepackage{upquote}                                                                    % switch curled `'" to straight
38\usepackage{calc}
39\usepackage{xspace}
40\usepackage{graphicx}
41\usepackage{varioref}                                                                   % extended references
42\usepackage{listings}                                                                   % format program code
43\usepackage[flushmargin]{footmisc}                                              % support label/reference in footnote
44\usepackage{latexsym}                                   % \Box glyph
45\usepackage{mathptmx}                                   % better math font with "times"
46\usepackage[usenames]{color}
47\usepackage[pagewise]{lineno}
48\renewcommand{\linenumberfont}{\scriptsize\sffamily}
49\input{common}                                          % bespoke macros used in the document
50\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref}
51\usepackage{breakurl}
52\renewcommand{\UrlFont}{\small\sf}
53
54\setlength{\topmargin}{-0.45in}                                                 % move running title into header
55\setlength{\headsep}{0.25in}
56
57%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
58
59% Names used in the document.
60
61\newcommand{\Version}{1.0.0}
62\newcommand{\CS}{C\raisebox{-0.9ex}{\large$^\sharp$}\xspace}
63
64\newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}}
65\newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}}
66\newcommand{\R}[1]{\Textbf{#1}}
67\newcommand{\B}[1]{{\Textbf[blue]{#1}}}
68\newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}}
69
70\newsavebox{\LstBox}
71
72%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
73
74\setcounter{secnumdepth}{3}                             % number subsubsections
75\setcounter{tocdepth}{3}                                % subsubsections in table of contents
76\makeindex
77
78%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
79
80\title{\Huge
81\vspace*{1in}
82\CFA (\CFL) User Manual                         \\
83Version 1.0                                                     \\
84\vspace*{0.25in}
85\huge``describe not prescribe''
86\vspace*{1in}
87}% title
88
89\author{\huge
90Peter A. Buhr and ...
91}% author
92
93\date{
94DRAFT \\ \today
95}% date
96
97%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
98
99\begin{document}
100\pagestyle{headings}
101% changed after setting pagestyle
102\renewcommand{\sectionmark}[1]{\markboth{\thesection\quad #1}{\thesection\quad #1}}
103\renewcommand{\subsectionmark}[1]{\markboth{\thesubsection\quad #1}{\thesubsection\quad #1}}
104\pagenumbering{roman}
105\linenumbers                                            % comment out to turn off line numbering
106
107\maketitle
108\thispagestyle{empty}
109\vspace*{\fill}
110\noindent
111\copyright\,2016 \CFA Project \\ \\
112\noindent
113This work is licensed under the Creative Commons Attribution 4.0 International License.
114To view a copy of this license, visit {\small\url{http://creativecommons.org/licenses/by/4.0}}.
115\vspace*{1in}
116
117\clearpage
118\thispagestyle{plain}
119\pdfbookmark[1]{Contents}{section}
120\tableofcontents
121
122\clearpage
123\thispagestyle{plain}
124\pagenumbering{arabic}
125
126
127\section{Introduction}
128
129\CFA\footnote{Pronounced ``C-for-all'', and written \CFA, CFA, or \CFL.} is a modern general-purpose programming-language, designed as an evolutionary step forward from the C programming language.
130The syntax of the \CFA language builds from C, and should look immediately familiar to C/\Index*[C++]{\CC} programmers.
131% Any language feature that is not described here can be assumed to be using the standard C11 syntax.
132\CFA adds many modern programming-language features that directly lead to increased \emph{safety} and \emph{productivity}, while maintaining interoperability with existing C programs and achieving C performance.
133Like C, \CFA is a statically typed, procedural language with a low-overhead runtime, meaning there is no global garbage-collection.
134The primary new features include parametric-polymorphic routines and types, exceptions, concurrency, and modules.
135
136One of the main design philosophies of \CFA is to ``describe not prescribe'', which means \CFA tries to provide a pathway from low-level C programming to high-level \CFA programming, but it does not force programmers to ``do the right thing''.
137Programmers can cautiously add \CFA extensions to their C programs in any order and at any time to incrementally move towards safer, higher-level programming features.
138A programmer is always free to reach back to C from \CFA for any reason, and in many cases, new \CFA features have a fallback to a C mechanism.
139There is no notion or requirement for rewriting a legacy C program in \CFA;
140instead, a programmer evolves an existing C program into \CFA by incrementally incorporating \CFA features.
141New programs can be written in \CFA using a combination of C and \CFA features.
142\Index*[C++]{\CC} had a similar goal 30 years ago, but has struggled over the intervening time to incorporate modern programming-language features because of early design choices.
143\CFA has 30 years of hindsight and a clean starting point.
144
145Like \Index*[C++]{\CC}, there may be both an old and new ways to achieve the same effect.
146For example, the following programs compare the \CFA and C I/O mechanisms.
147\begin{quote2}
148\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
149\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
150\begin{lstlisting}
151#include <fstream>
152int main( void ) {
153        int x = 0, y = 1, z = 2;
154        ®sout | x | y | z | endl;®
155}
156\end{lstlisting}
157&
158\begin{lstlisting}
159#include <stdio.h>
160int main( void ) {
161        int x = 0, y = 1, z = 2;
162        ®printf( "%d %d %d\n", x, y, z );®
163}
164\end{lstlisting}
165\end{tabular}
166\end{quote2}
167Both programs output the same result.
168While the \CFA I/O looks similar to the \Index*[C++]{\CC} output style, there are important differences, such as automatic spacing between variables as in \Index*{Python} (see also~\VRef{s:IOLibrary}).
169
170This document is a user manual for the \CFA programming language, targeted at \CFA programmers.
171Implementers may refer to the \CFA Programming Language Specification for details about the language syntax and semantics.
172In its current state, this document covers the intended core features of the language.
173Changes to the syntax and additional features are expected to be included in later revisions.
174% For additional information, see \url{http://wiki.do-lang.org}.
175
176
177\section{History}
178
179The \CFA project started with K-W C~\cite{Buhr94a,Till89}, which extended C with new declaration syntax, multiple return values from routines, and extended assignment capabilities using the notion of tuples.
180(See~\cite{Werther96} for some similar work, but for \Index*[C++]{\CC}.)
181The original \CFA project~\cite{Ditchfield92} extended the C type system with parametric polymorphism and overloading, as opposed to the \Index*[C++]{\CC} approach of object-oriented extensions to the C type-system.
182A first implementation of the core Cforall language was created~\cite{Bilson03,Esteves04}, but at the time there was little interesting in extending C, so work did not continue.
183As the saying goes, ``What goes around, comes around.'', and there is now renewed interest in the C programming language because of legacy code-bases, so the \CFA project has been restarted.
184
185
186\section{Why fix C?}
187
188Even with all its problems, C is a very popular programming language because it allows writing software at virtually any level in a computer system without restriction.
189For system programming, where direct access to hardware and dealing with real-time issues is a requirement, C is usually the language of choice.
190As well, there are millions of lines of C legacy code, forming the base for many software development projects (especially on UNIX systems).
191The TIOBE index (\url{http://www.tiobe.com/tiobe_index}) for March 2016 shows programming-language popularity, with \Index*{Java} 20.5\%, C 14.5\%, \Index*[C++]{\CC} 6.7\%, \CS 4.3\%, \Index*{Python} 4.3\%, and all other programming languages below 3\%.
192As well, for 30 years, C has been the number 1 and 2 most popular programming language:
193\begin{center}
194\setlength{\tabcolsep}{1.5ex}
195\begin{tabular}{@{}r|c|c|c|c|c|c|c@{}}
196Ranking & 2016  & 2011  & 2006  & 2001  & 1996  & 1991  & 1986          \\
197\hline
198Java    & 1             & 1             & 1             & 3             & 29    & -             & -                     \\
199\hline
200\R{C}   & \R{2} & \R{2} & \R{2} & \R{1} & \R{1} & \R{1} & \R{1}         \\
201\hline
202\CC             & 3             & 3             & 3             & 2             & 2             & 2             & 7                     \\
203\end{tabular}
204\end{center}
205Hence, C is still an extremely important programming language, with double the usage of \Index*[C++]{\CC}, where \CC itself is largely C code.
206Finally, love it or hate it, C has been an important and influential part of computer science for 40 years and it appears it will continue to be for many more years.
207Unfortunately, C has too many problems and omissions to make it an acceptable programming language for modern needs.
208
209The goal of this project is to engineer modern language features into C in an evolutionary rather than revolutionary way.
210\CC~\cite{c++,ANSI14:C++} is an example of a similar project;
211however, it largely extended the language, and did not address many existing problems.\footnote{%
212Two important existing problems addressed were changing the type of character literals from ©int© to ©char© and enumerator from ©int© to the type of its enumerators.}
213\Index*{Fortran}~\cite{Fortran08}, \Index*{Ada}~\cite{Ada12}, and \Index*{Cobol}~\cite{Cobol14} are examples of programming languages that took an evolutionary approach, where modern language features (e.g., objects, concurrency) are added and problems fixed within the framework of the existing language.
214\Index*{Java}~\cite{Java8}, \Index*{Go}~\cite{Go}, \Index*{Rust}~\cite{Rust} and \Index*{D}~\cite{D} are examples of the revolutionary approach for modernizing C/\CC, resulting in a new language rather than an extension of the descendent.
215These languages have different syntax and semantics from C, and do not interoperate directly with C, largely because of garbage collection.
216As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten.
217These costs can be prohibitive for many companies with a large software base in C/\CC, and a significant number of programmers requiring retraining to a new programming language.
218
219The result of this project is a language that is largely backwards compatible with C11~\cite{C11}, but fixing some of the well known C problems and containing many modern language features.
220Without significant extension to the C programming language, it is becoming unable to cope with the needs of modern programming problems and programmers;
221as a result, it will fade into disuse.
222Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language.
223While C11 made a few simple extensions to the language, nothing was added to address existing problems in the language or to augment the language with modern language features.
224While some may argue that modern language features may make C complex and inefficient, it is clear a language without modern capabilities is insufficient for the advanced programming problems existing today.
225
226
227\section{Interoperability}
228
229\CFA is designed to integrate well with existing C programs and libraries.
230The most important feature of interoperability is to use the same calling conventions, so there is no overhead to call existing C routines.
231This feature allows users of \CFA to take advantage of the existing panoply of C libraries from inside their \CFA code.
232In fact, one of the biggest issues for any new programming language is establishing a minimum level of library code to support a large body of activities.
233Language developers often state that adequate library support takes more work than designing and implementing the language itself.
234Like \Index*[C++]{\CC}, \CFA starts with immediate access to all exiting C libraries, and in many cases, can easily wrap library routines with simpler and safer interfaces, at very low cost.
235Hence, \CFA begins by leveraging the large repository of C libraries with little cost.
236
237However, it is necessary to differentiate between C and \CFA code because of name overloading, as for \CC.
238For example, the C math-library provides the following routines for computing the absolute value of the basic types: ©abs©, ©labs©, ©llabs©, ©fabs©, ©fabsf©, ©fabsl©, ©cabsf©, ©cabs©, and ©cabsl©.
239Whereas, \CFA wraps each of these routines into ones with the common name ©abs©:
240\begin{lstlisting}
241char abs( char );
242extern "C" {
243int abs( int );                                 §\C{// use default C routine for int}§
244} // extern "C"
245long int abs( long int );
246long long int abs( long long int );
247float abs( float );
248double abs( double );
249long double abs( long double );
250float _Complex abs( float _Complex );
251double _Complex abs( double _Complex );
252long double _Complex abs( long double _Complex );
253\end{lstlisting}
254The problem is the name clash between the library routine ©abs© and the \CFA names ©abs©.
255Hence, names appearing in an ©extern "C"© block have \newterm*{C linkage}.
256Then overloading polymorphism uses a mechanism called \newterm{name mangling}\index{mangling!name} to create unique names that are different from C names, which are not mangled.
257Hence, there is the same need as in \CC, to know if a name is a C or \CFA name, so it can be correctly formed.
258There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type.
259This example strongly illustrates a core idea in \CFA: \emph{the power of a name}.
260The name ``©abs©'' evokes the notion of absolute value, and many mathematical types provide the notion of absolute value.
261Hence, knowing the name ©abs© should be sufficient to apply it to any type where it is applicable.
262The time savings and safety of using one name uniformly versus $N$ unique names should not be underestimated.
263
264
265\section[Compiling CFA Program]{Compiling \CFA Program}
266
267The command ©cfa© is used to compile \CFA program(s), and is based on the GNU \Indexc{gcc} command, e.g.:
268\begin{lstlisting}
269cfa§\indexc{cfa}\index{compilation!cfa@©cfa©}§ [ gcc-options ] C/§\CFA§-files [ assembler/loader-files ]
270\end{lstlisting}
271\CFA programs having the following ©gcc© flags turned on:
272\begin{description}
273\item
274\Indexc{-std=gnu99}\index{compilation option!-std=gnu99@{©-std=gnu99©}}
275The 1999 C standard plus GNU extensions.
276\item
277\Indexc{-fgnu89-inline}\index{compilation option!-fgnu89-inline@{©-fgnu89-inline©}}
278Use the traditional GNU semantics for inline routines in C99 mode, which allows inline routines in header files.
279\end{description}
280The following new \CFA options are available:
281\begin{description}
282\item
283\Indexc{-CFA}\index{compilation option!-CFA@©-CFA©}
284Only the C preprocessor and the \CFA translator steps are performed and the transformed program is written to standard output, which makes it possible to examine the code generated by the \CFA translator.
285The generated code started with the standard \CFA prelude.
286
287\item
288\Indexc{-debug}\index{compilation option!-debug@©-debug©}
289The program is linked with the debugging version of the runtime system.
290The debug version performs runtime checks to help during the debugging phase of a \CFA program, but substantially slows the execution of the program.
291The runtime checks should only be removed after the program is completely debugged.
292\textbf{This option is the default.}
293
294\item
295\Indexc{-nodebug}\index{compilation option!-nodebug@©-nodebug©}
296The program is linked with the non-debugging version of the unikernel or multikernel, so the execution of the program is faster.
297\Emph{However, no runtime checks or ©assert©s are performed so errors usually result in abnormal program termination.}
298
299\item
300\Indexc{-help}\index{compilation option!-help@©-help©}
301Information about the set of \CFA compilation flags is printed.
302
303\item
304\Indexc{-nohelp}\index{compilation option!-nohelp@©-nohelp©}
305Information about the set of \CFA compilation flags is not printed.
306\textbf{This option is the default.}
307
308\item
309\Indexc{-quiet}\index{compilation option!-quiet@©-quiet©}
310The \CFA compilation message is not printed at the beginning of a compilation.
311
312\item
313\Indexc{-noquiet}\index{compilation option!-noquiet@©-noquiet©}
314The \CFA compilation message is printed at the beginning of a compilation.
315\textbf{This option is the default.}
316\end{description}
317
318The following preprocessor variables are available:
319\begin{description}
320\item
321\Indexc{__CFA__}\index{preprocessor variables!__CFA__@{©__CFA__©}}
322is always available during preprocessing and its value is the current major \Index{version number} of \CFA.\footnote{
323The C preprocessor allows only integer values in a preprocessor variable so a value like ``\Version'' is not allowed.
324Hence, the need to have three variables for the major, minor and patch version number.}
325
326\item
327\Indexc{__CFA_MINOR__}\index{preprocessor variables!__CFA_MINOR__@{©__CFA_MINOR__©}}
328is always available during preprocessing and its value is the current minor \Index{version number} of \CFA.
329
330\item
331\Indexc{__CFA_PATCH__}\index{preprocessor variables!__CFA_PATCH____CFA_PATCH__©}
332is always available during preprocessing and its value is the current patch \Index{version number} of \CFA.
333
334\item
335\Indexc{__CFORALL__}\index{preprocessor variables!__CFORALL____CFORALL__©}
336is always available during preprocessing and has no value.
337\end{description}
338These preprocessor variables allow conditional compilation of programs that must work differently in these situations.
339For example, to toggle between C and \CFA extensions, using the following:
340\begin{lstlisting}
341#ifndef __CFORALL__
342#include <stdio.h>                              §\C{// C header file}§
343#else
344#include <fstream>                              §\C{// \CFA header file}§
345#endif
346\end{lstlisting}
347which conditionally includes the correct header file, if the program is compiled using \Indexc{gcc} or \Indexc{cfa}.
348
349
350\section{Underscores in Constants}
351
352Numeric constants are extended to allow \Index{underscore}s within constants\index{constant!underscore}, e.g.:
353\begin{lstlisting}
354_®147®_®483®_®648;                    §\C{// decimal constant}§
35556_ul;                                                  §\C{// decimal unsigned long constant}§
3560_377;                                                  §\C{// octal constant}§
3570x_ff_ff;                                               §\C{// hexadecimal constant}§
3580x_ef3d_aa5c;                                   §\C{// hexadecimal constant}§
3593.141_592_654;                                  §\C{// floating point constant}§
36010_e_+1_00;                                             §\C{// floating point constant}§
3610x_ff_ff_p_3;                                   §\C{// hexadecimal floating point}§
3620x_1.ffff_ffff_p_128_l;                 §\C{// hexadecimal floating point long constant}§
363L_"\x_ff_ee";                                   §\C{// wide character constant}§
364\end{lstlisting}
365The rules for placement of underscores is as follows:
366\begin{enumerate}
367\item
368A sequence of underscores is disallowed, e.g., ©12__34© is invalid.
369\item
370Underscores may only appear within a sequence of digits (regardless of the digit radix).
371In other words, an underscore cannot start or end a sequence of digits, e.g., ©_1©, ©1_© and ©_1_© are invalid (actually, the 1st and 3rd examples are identifier names).
372\item
373A numeric prefix may end with an underscore;
374a numeric infix may begin and/or end with an underscore;
375a numeric suffix may begin with an underscore.
376For example, the octal ©0© or hexadecimal ©0x© prefix may end with an underscore ©0_377© or ©0x_ff©;
377the exponent infix ©E© may start or end with an underscore ©1.0_E10©, ©1.0E_10© or ©1.0_E_10©;
378the type suffixes ©U©, ©L©, etc. may start with an underscore ©1_U©, ©1_ll© or ©1.0E10_f©.
379\end{enumerate}
380It is significantly easier to read and enter long constants when they are broken up into smaller groupings (most cultures use comma or period among digits for the same purpose).
381This extension is backwards compatible, matches with the use of underscore in variable names, and appears in \Index*{Ada} and \Index*{Java} 8.
382
383
384\section{Declarations}
385\label{s:Declarations}
386
387C declaration syntax is notoriously confusing and error prone.
388For example, many C programmers are confused by a declaration as simple as:
389\begin{quote2}
390\begin{tabular}{@{}ll@{}}
391\begin{lstlisting}
392int *x[5]
393\end{lstlisting}
394&
395\raisebox{-0.75\totalheight}{\input{Cdecl}}
396\end{tabular}
397\end{quote2}
398Is this an array of 5 pointers to integers or a \Index{pointer} to an array of 5 integers?
399The fact this declaration is unclear to many C programmers means there are \Index{productivity} and \Index{safety} issues even for basic programs.
400Another example of confusion results from the fact that a routine name and its parameters are embedded within the return type, mimicking the way the return value is used at the routine's call site.
401For example, a routine returning a \Index{pointer} to an array of integers is defined and used in the following way:
402\begin{lstlisting}
403int (*f())[5] {...};                    §\C{}§
404... (*f())[3] += 1;
405\end{lstlisting}
406Essentially, the return type is wrapped around the routine name in successive layers (like an onion).
407While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice.
408
409\CFA provides its own type, variable and routine declarations, using a different syntax.
410The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right of the base type.
411In the following example, \R{red} is for the base type and \B{blue} is for the qualifiers.
412The \CFA declarations move the qualifiers to the left of the base type, i.e., move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type.
413\begin{quote2}
414\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
415\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
416\begin{lstlisting}
417ß[5] *ß ®int® x1;
418ß* [5]ß ®int® x2;
419ß[* [5] int]ß f®( int p )®;
420\end{lstlisting}
421&
422\begin{lstlisting}
423®int® ß*ß x1 ß[5]ß;
424®int® ß(*ßx2ß)[5]ß;
425ßint (*ßf®( int p )®ß)[5]ß;
426\end{lstlisting}
427\end{tabular}
428\end{quote2}
429The only exception is bit field specification, which always appear to the right of the base type.
430% Specifically, the character ©*© is used to indicate a pointer, square brackets ©[©\,©]© are used to represent an array or function return value, and parentheses ©()© are used to indicate a routine parameter.
431However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list.
432For instance, variables ©x© and ©y© of type \Index{pointer} to integer are defined in \CFA as follows:
433\begin{quote2}
434\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
435\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
436\begin{lstlisting}
437®*® int x, y;
438\end{lstlisting}
439&
440\begin{lstlisting}
441int ®*®x, ®*®y;
442\end{lstlisting}
443\end{tabular}
444\end{quote2}
445The downside of this semantics is the need to separate regular and \Index{pointer} declarations:
446\begin{quote2}
447\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
448\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
449\begin{lstlisting}
450®*® int x;
451int y;
452\end{lstlisting}
453&
454\begin{lstlisting}
455int ®*®x, y;
456
457\end{lstlisting}
458\end{tabular}
459\end{quote2}
460which is \Index{prescribing} a safety benefit.
461Other examples are:
462\begin{quote2}
463\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
464\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
465\begin{lstlisting}
466[ 5 ] int z;
467[ 5 ] * char w;
468* [ 5 ] double v;
469struct s {
470        int f0:3;
471        * int f1;
472        [ 5 ] * int f2;
473};
474\end{lstlisting}
475&
476\begin{lstlisting}
477int z[ 5 ];
478char *w[ 5 ];
479double (*v)[ 5 ];
480struct s {
481        int f0:3;
482        int *f1;
483        int *f2[ 5 ]
484};
485\end{lstlisting}
486&
487\begin{lstlisting}
488// array of 5 integers
489// array of 5 pointers to char
490// pointer to array of 5 doubles
491
492// common bit field syntax
493
494
495
496\end{lstlisting}
497\end{tabular}
498\end{quote2}
499
500All type qualifiers, e.g., ©const©, ©volatile©, etc., are used in the normal way with the new declarations and also appear left to right, e.g.:
501\begin{quote2}
502\begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}}
503\multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\
504\begin{lstlisting}
505const * const int x;
506const * [ 5 ] const int y;
507\end{lstlisting}
508&
509\begin{lstlisting}
510int const * const x;
511const int (* const y)[ 5 ]
512\end{lstlisting}
513&
514\begin{lstlisting}
515// const pointer to const integer
516// const pointer to array of 5 const integers
517\end{lstlisting}
518\end{tabular}
519\end{quote2}
520All declaration qualifiers, e.g., ©extern©, ©static©, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier}
521The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}} e.g.:
522\begin{quote2}
523\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
524\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
525\begin{lstlisting}
526extern [ 5 ] int x;
527static * const int y;
528\end{lstlisting}
529&
530\begin{lstlisting}
531int extern x[ 5 ];
532const int static *y;
533\end{lstlisting}
534&
535\begin{lstlisting}
536// externally visible array of 5 integers
537// internally visible pointer to constant int
538\end{lstlisting}
539\end{tabular}
540\end{quote2}
541
542Unsupported are K\&R C declarations where the base type defaults to ©int©, if no type is specified,\footnote{
543At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each structure declaration and type name~\cite[\S~6.7.2(2)]{C11}}
544e.g.:
545\begin{lstlisting}
546x;                                                              §\C{// int x}§
547*y;                                                             §\C{// int *y}§
548f( p1, p2 );                                    §\C{// int f( int p1, int p2 );}§
549f( p1, p2 ) {}                                  §\C{// int f( int p1, int p2 ) {}}§
550\end{lstlisting}
551
552Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration.
553Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style.
554Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems.
555
556
557\section{Pointer / Reference}
558
559C provides a \newterm{pointer type};
560\CFA adds a \newterm{reference type}.
561Both types contain an \newterm{address}, which is normally a location in memory.
562Special addresses are used to denote certain states or access co-processor memory.
563By convention, no variable is placed at address 0, so addresses like 0, 1, 2, 3 are often used to denote no-value or other special states.
564Often dereferencing a special state causes a \Index{memory fault}, so checking is necessary during execution.
565If the programming language assigns addresses, a program's execution is \Index{sound}, i.e., all addresses are to valid memory locations.
566C allows programmers to assign addresses, so there is the potential for incorrect addresses, both inside and outside of the computer address-space.
567
568Program variables are implicit pointers to memory locations generated by the compiler and automatically dereferenced, as in:
569\begin{quote2}
570\begin{tabular}{@{}lll@{}}
571\begin{lstlisting}
572int x;
573x = 3;
574int y;
575y = x;
576\end{lstlisting}
577&
578\raisebox{-0.45\totalheight}{\input{pointer1}}
579&
580\begin{lstlisting}
581int * ®const® x = (int *)100
582*x = 3;                 // implicit dereference
583int * ®const® y = (int *)104;
584*y = *x;                // implicit dereference
585\end{lstlisting}
586\end{tabular}
587\end{quote2}
588where the right example is how the compiler logically interprets the variables in the left example.
589Since a variable name only points to one location during its lifetime, it is an \Index{immutable} \Index{pointer};
590hence, variables ©x© and ©y© are constant pointers in the compiler interpretation.
591In general, variable addresses are stored in instructions instead of loaded independently, so an instruction fetch implicitly loads a variable's address.
592\begin{quote2}
593\begin{tabular}{@{}l|l@{}}
594\begin{lstlisting}
595lda             r1,100                  // load address of x
596ld              r2,(r1)                   // load value of x
597lda             r3,104                  // load address of y
598st              r2,(r3)                   // store x into y
599\end{lstlisting}
600&
601\begin{lstlisting}
602
603ld              r2,(100)                // load value of x
604
605st              r2,(104)                // store x into y
606\end{lstlisting}
607\end{tabular}
608\end{quote2}
609Finally, the immutable nature of a variable's address and the fact that there is no storage for a variable address means pointer assignment\index{pointer!assignment}\index{assignment!pointer} is impossible.
610Therefore, the expression ©x = y© only has one meaning, ©*x = *y©, i.e., manipulate values, which is why explicitly writing the dereferences is unnecessary even though it occurs implicitly as part of instruction decoding.
611
612A \Index{pointer}/\Index{reference} is a generalization of a variable name, i.e., a mutable address that can point to more than one memory location during its lifetime.
613(Similarly, an integer variable can contain multiple integer literals during its lifetime versus an integer constant representing a single literal during its lifetime and may not occupy storage as the literal is embedded directly into instructions.)
614Hence, a pointer occupies memory to store its current address, and the pointer's value is loaded by dereferencing, e.g.:
615\begin{quote2}
616\begin{tabular}{@{}ll@{}}
617\begin{lstlisting}
618int x, y, ®*® p1, ®*® p2, ®**® p3;
619p1 = ®&®x;               // p1 points to x
620p2 = p1;                 // p2 points to x
621p1 = ®&®y;               // p1 points to y
622p3 = &p2;               // p3 points to p2
623\end{lstlisting}
624&
625\raisebox{-0.45\totalheight}{\input{pointer2.pstex_t}}
626\end{tabular}
627\end{quote2}
628
629Notice, an address has a duality\index{address!duality}: a location in memory or the value at that location.
630In many cases, a compiler might be able to infer the meaning:
631\begin{lstlisting}
632p2 = p1 + x;                                    §\C{// compiler infers *p2 = *p1 + x;}§
633\end{lstlisting}
634because adding the arbitrary integer value in ©x© to the address of ©p1© and storing the resulting address into ©p2© is an unlikely operation.
635\Index*{Algol68}~\cite{Algol68} inferences pointer dereferencing to select the best meaning for each pointer usage.
636However, in C, the following cases are ambiguous, especially with pointer arithmetic:
637\begin{lstlisting}
638p1 = p2;                                                §\C{// p1 = p2\ \ or\ \ *p1 = *p2}§
639p1 = p1 + 1;                                    §\C{// p1 = p1 + 1\ \ or\ \ *p1 = *p1 + 1}§
640\end{lstlisting}
641
642Most languages pick one meaning as the default and the programmer explicitly indicates the other meaning to resolve the address-duality ambiguity\index{address! ambiguity}.
643In C, the default meaning for pointers is to manipulate the pointer's address and the pointed-to value is explicitly accessed by the dereference operator ©*©.
644\begin{lstlisting}
645p1 = p2;                                                §\C{// pointer address assignment}§
646*p1 = *p1 + 1;                                  §\C{// pointed-to value assignment / operation}§
647\end{lstlisting}
648which works well for situations where manipulation of addresses is the primary meaning and data is rarely accessed, such as storage management (©malloc©/©free©).
649
650However, in most other situations, the pointed-to value is requested more often than the pointer address.
651\begin{lstlisting}
652*p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15);
653\end{lstlisting}
654In this case, it is tedious to explicitly write the dereferencing, and error prone when pointer arithmetic is allowed.
655It is better to have the compiler generate the dereferencing and have no implicit pointer arithmetic:
656\begin{lstlisting}
657p2 = ((p1 + p2) * (p3 - p1)) / (p3 - 15);
658\end{lstlisting}
659
660To switch the default meaning for an address requires a new kind of pointer, called a \newterm{reference} denoted by ©&©.
661\begin{lstlisting}
662int x, y, ®&® r1, ®&® r2, ®&&® r3;
663®&®r1 = &x;                                             §\C{// r1 points to x}§
664®&®r2 = &r1;                                    §\C{// r2 points to x}§
665®&®r1 = &y;                                             §\C{// r1 points to y}§
666®&&®r3 = ®&®&r2;                                §\C{// r3 points to r2}§
667r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15); §\C{// implicit dereferencing}§
668\end{lstlisting}
669Except for auto-dereferencing by the compiler, this reference example is the same as the previous pointer example.
670Hence, a reference behaves like the variable name for the current variable it is pointing-to.
671The simplest way to understand a reference is to imagine the compiler inserting a dereference operator before the reference variable for each reference qualifier in a declaration, e.g.:
672\begin{lstlisting}
673r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15);
674\end{lstlisting}
675is rewritten as:
676\begin{lstlisting}
677®*®r2 = ((®*®r1 + ®*®r2) ®*® (®**®r3 - ®*®r1)) / (®**®r3 - 15);
678\end{lstlisting}
679When a reference operation appears beside a dereference operation, e.g., ©&*©, they cancel out.\footnote{
680The unary ©&© operator yields the address of its operand.
681If the operand has type ``type'', the result has type ``pointer to type''.
682If the operand is the result of a unary ©*© operator, neither that operator nor the ©&© operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.~\cite[\S~6.5.3.2--3]{C11}}
683Hence, assigning to a reference requires the address of the reference variable (\Index{lvalue}):
684\begin{lstlisting}
685(&®*®)r1 = &x;                                  §\C{// (\&*) cancel giving variable r1 not variable pointed-to by r1}§
686\end{lstlisting}
687Similarly, the address of a reference can be obtained for assignment or computation (\Index{rvalue}):
688\begin{lstlisting}
689(&(&®*®)®*®)r3 = &(&®*®)r2;             §\C{// (\&*) cancel giving address of r2, (\&(\&*)*) cancel giving variable r3}§
690\end{lstlisting}
691Cancellation\index{cancellation!pointer/reference}\index{pointer!cancellation} works to arbitrary depth, and pointer and reference values are interchangeable because both contain addresses.
692\begin{lstlisting}
693int x, *p1 = &x, **p2 = &p1, ***p3 = &p2,
694                 &r1 = x,    &&r2 = r1,   &&&r3 = r2;
695***p3 = 3;                                              §\C{// change x}§
696r3 = 3;                                                 §\C{// change x, ***r3}§
697**p3 = ...;                                             §\C{// change p1}§
698&r3 = ...;                                              §\C{// change r1, (\&*)**r3, 1 cancellation}§
699*p3 = ...;                                              §\C{// change p2}§
700&&r3 = ...;                                             §\C{// change r2, (\&(\&*)*)*r3, 2 cancellations}§
701&&&r3 = p3;                                             §\C{// change r3 to p3, (\&(\&(\&*)*)*)r3, 3 cancellations}§
702\end{lstlisting}
703Finally, implicit dereferencing and cancellation are a static (compilation) phenomenon not a dynamic one.
704That is, all implicit dereferencing and any cancellation is carried out prior to the start of the program, so reference performance is equivalent to pointer performance.
705A programmer selects a pointer or reference type solely on whether the address is dereferenced frequently or infrequently, which dictates the amount of direct aid from the compiler;
706otherwise, everything else is equal.
707
708Interestingly, \Index*[C++]{\CC} deals with the address duality by making the pointed-to value the default, and prevent\-ing changes to the reference address, which eliminates half of the duality.
709\Index*{Java} deals with the address duality by making address assignment the default and requiring field assignment (direct or indirect via methods), i.e., there is no builtin bit-wise or method-wise assignment, which eliminates half of the duality.
710
711As for a pointer, a reference may have qualifiers:
712\begin{lstlisting}
713const int cx = 5;                               §\C{// cannot change cx;}§
714const int & cr = cx;                    §\C{// cannot change what cr points to}§
715®&®cr = &cx;                                    §\C{// can change cr}§
716cr = 7;                                                 §\C{// error, cannot change cx}§
717int & const rc = x;                             §\C{// must be initialized, \CC reference}§
718®&®rc = &x;                                             §\C{// error, cannot change rc}§
719const int & const crc = cx;             §\C{// must be initialized, \CC reference}§
720crc = 7;                                                §\C{// error, cannot change cx}§
721®&®crc = &cx;                                   §\C{// error, cannot change crc}§
722\end{lstlisting}
723Hence, for type ©& const©, there is no pointer assignment, so ©&rc = &x© is disallowed, and \emph{the address value cannot be ©0© unless an arbitrary pointer is assigned to the reference}.
724In effect, the compiler is managing the addresses for type ©& const© not the programmer, and by a programming discipline of only using references with references, address errors can be prevented.
725
726\Index{Initialization} is different than \Index{assignment} because initialization occurs on the empty (uninitialized) storage on an object, while assignment occurs on possibly initialized storage of an object.
727There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, return/temporary binding.
728For reference initialization (like pointer), the initializing value must be an address (\Index{lvalue}) not a value (\Index{rvalue}).
729\begin{lstlisting}
730int * p = &x;                                   §\C{// both \&x and x are possible interpretations}§
731int & r = x;                                    §\C{// x unlikely interpretation, because of auto-dereferencing}§
732\end{lstlisting}
733Hence, the compiler implicitly inserts a reference operator, ©&©, before the initialization expression.
734Similarly, when a reference is used for a parameter/return type, the call-site argument does not require a reference operator.
735\begin{lstlisting}
736int & f( int & rp );                    §\C{// reference parameter and return}§
737z = f( x ) + f( y );                    §\C{// reference operator added}§
738\end{lstlisting}
739Within routine ©f©, it is possible to change the argument by changing the corresponding parameter, and parameter ©rp© can be locally reassigned within ©f©.
740The return reference from ©f© is copied into a compiler generated temporary, which is treated as an initialization.
741
742When a pointer/reference parameter has a ©const© value (immutable), it is possible to pass literals and expressions.
743\begin{lstlisting}
744void f( ®const® int & crp );
745void g( ®const® int * cpp );
746f( 3 );                   g( &3 );
747f( x + y );             g( &(x + y) );
748\end{lstlisting}
749Here, the compiler passes the address to the literal 3 or the temporary for the expression ©x + y©, knowing the argument cannot be changed through the parameter.
750(The ©&© is necessary for the pointer parameter to make the types match, and is a common requirement for a C programmer.)
751\CFA \emph{extends} this semantics to a mutable pointer/reference parameter, and the compiler implicitly creates the necessary temporary (copying the argument), which is subsequently pointed-to by the reference parameter and can be changed.
752\begin{lstlisting}
753void f( int & rp );
754void g( int * pp );
755f( 3 );                   g( &3 );              §\C{// compiler implicit generates temporaries}§
756f( x + y );             g( &(x + y) );  §\C{// compiler implicit generates temporaries}§
757\end{lstlisting}
758Essentially, there is an implicit \Index{rvalue} to \Index{lvalue} conversion in this case.\footnote{
759This conversion attempts to address the \newterm{const hell} problem, when the innocent addition of a ©const© qualifier causes a cascade of type failures, requiring an unknown number of additional ©const© qualifiers, until it is discovered a ©const© qualifier cannot be added and all the ©const© qualifiers must be removed.}
760The implicit conversion allows seamless calls to any routine without having to explicitly name/copy the literal/expression to allow the call.
761
762While \CFA attempts to handle pointers and references in a uniform, symmetric manner, C handles routine variables in an inconsistent way: a routine variable is both a pointer and a reference (particle and wave).
763\begin{lstlisting}
764void f( int p ) {...}
765void (*fp)( int ) = &f;                 §\C{// pointer initialization}§
766void (*fp)( int ) = f;                  §\C{// reference initialization}§
767(*fp)(3);                                               §\C{// pointer invocation}§
768fp(3);                                                  §\C{// reference invocation}§
769\end{lstlisting}
770A routine variable is best described by a ©const© reference:
771\begin{lstlisting}
772const void (&fp)( int ) = f;
773fp( 3 );
774fp = ...                                                §\C{// error, cannot change code}§
775&fp = ...;                                              §\C{// changing routine reference}§
776\end{lstlisting}
777because the value of the routine variable is a routine literal, i.e., the routine code is normally immutable during execution.\footnote{
778Dynamic code rewriting is possible but only in special circumstances.}
779\CFA allows this additional use of references for routine variables in an attempt to give a more consistent meaning for them.
780
781
782\section{Type Operators}
783
784The new declaration syntax can be used in other contexts where types are required, e.g., casts and the pseudo-routine ©sizeof©:
785\begin{quote2}
786\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
787\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
788\begin{lstlisting}
789y = (®* int®)x;
790i = sizeof(®[ 5 ] * int®);
791\end{lstlisting}
792&
793\begin{lstlisting}
794y = (®int *®)x;
795i = sizeof(®int *[ 5 ]®);
796\end{lstlisting}
797\end{tabular}
798\end{quote2}
799
800
801\section{Routine Definition}
802
803\CFA also supports a new syntax for routine definition, as well as ISO C and K\&R routine syntax.
804The point of the new syntax is to allow returning multiple values from a routine~\cite{Galletly96,CLU}, e.g.:
805\begin{lstlisting}
806®[ int o1, int o2, char o3 ]® f( int i1, char i2, char i3 ) {
807        §\emph{routine body}§
808}
809\end{lstlisting}
810where routine ©f© has three output (return values) and three input parameters.
811Existing C syntax cannot be extended with multiple return types because it is impossible to embed a single routine name within multiple return type specifications.
812
813In detail, the brackets, ©[]©, enclose the result type, where each return value is named and that name is a local variable of the particular return type.\footnote{
814\Index*{Michael Tiemann}, with help from \Index*{Doug Lea}, provided named return values in g++, circa 1989.}
815The value of each local return variable is automatically returned at routine termination.
816Declaration qualifiers can only appear at the start of a routine definition, e.g.:
817\begin{lstlisting}
818®extern® [ int x ] g( int y ) {§\,§}
819\end{lstlisting}
820Lastly, if there are no output parameters or input parameters, the brackets and/or parentheses must still be specified;
821in both cases the type is assumed to be void as opposed to old style C defaults of int return type and unknown parameter types, respectively, as in:
822\begin{lstlisting}
823\,§] g();                                             §\C{// no input or output parameters}§
824[ void ] g( void );                             §\C{// no input or output parameters}§
825\end{lstlisting}
826
827Routine f is called as follows:
828\begin{lstlisting}
829[ i, j, ch ] = f( 3, 'a', ch );
830\end{lstlisting}
831The list of return values from f and the grouping on the left-hand side of the assignment is called a \newterm{return list} and discussed in Section 12.
832
833\CFA style declarations cannot be used to declare parameters for K\&R style routine definitions because of the following ambiguity:
834\begin{lstlisting}
835int (*f(x))[ 5 ] int x; {}
836\end{lstlisting}
837The string ``©int (*f(x))[ 5 ]©'' declares a K\&R style routine of type returning a pointer to an array of 5 integers, while the string ``©[ 5 ] int x©'' declares a \CFA style parameter x of type array of 5 integers.
838Since the strings overlap starting with the open bracket, ©[©, there is an ambiguous interpretation for the string.
839As well, \CFA-style declarations cannot be used to declare parameters for C-style routine-definitions because of the following ambiguity:
840\begin{lstlisting}
841typedef int foo;
842int f( int (* foo) );                   §\C{// foo is redefined as a parameter name}§
843\end{lstlisting}
844The string ``©int (* foo)©'' declares a C-style named-parameter of type pointer to an integer (the parenthesis are superfluous), while the same string declares a \CFA style unnamed parameter of type routine returning integer with unnamed parameter of type pointer to foo.
845The redefinition of a type name in a parameter list is the only context in C where the character ©*© can appear to the left of a type name, and \CFA relies on all type qualifier characters appearing to the right of the type name.
846The inability to use \CFA declarations in these two contexts is probably a blessing because it precludes programmers from arbitrarily switching between declarations forms within a declaration contexts.
847
848C-style declarations can be used to declare parameters for \CFA style routine definitions, e.g.:
849\begin{lstlisting}
850[ int ] f( * int, int * );              §\C{// returns an integer, accepts 2 pointers to integers}§
851[ * int, int * ] f( int );              §\C{// returns 2 pointers to integers, accepts an integer}§
852\end{lstlisting}
853The reason for allowing both declaration styles in the new context is for backwards compatibility with existing preprocessor macros that generate C-style declaration-syntax, as in:
854\begin{lstlisting}
855#define ptoa( n, d ) int (*n)[ d ]
856int f( ptoa( p, 5 ) ) ...               §\C{// expands to int f( int (*p)[ 5 ] )}§
857[ int ] f( ptoa( p, 5 ) ) ...   §\C{// expands to [ int ] f( int (*p)[ 5 ] )}§
858\end{lstlisting}
859Again, programmers are highly encouraged to use one declaration form or the other, rather than mixing the forms.
860
861
862\subsection{Named Return Values}
863
864\Index{Named return values} handle the case where it is necessary to define a local variable whose value is then returned in a ©return© statement, as in:
865\begin{lstlisting}
866int f() {
867        int x;
868        ... x = 0; ... x = y; ...
869        return x;
870}
871\end{lstlisting}
872Because the value in the return variable is automatically returned when a \CFA routine terminates, the ©return© statement \emph{does not} contain an expression, as in:
873\newline
874\begin{minipage}{\linewidth}
875\begin{lstlisting}
876®[ int x, int y ]® f() {
877        int z;
878        ... x = 0; ... y = z; ...
879        ®return;® §\C{// implicitly return x, y}§
880}
881\end{lstlisting}
882\end{minipage}
883\newline
884When the return is encountered, the current values of ©x© and ©y© are returned to the calling routine.
885As well, ``falling off the end'' of a routine without a ©return© statement is permitted, as in:
886\begin{lstlisting}
887[ int x, int y ] f() {
888        ...
889} §\C{// implicitly return x, y}§
890\end{lstlisting}
891In this case, the current values of ©x© and ©y© are returned to the calling routine just as if a ©return© had been encountered.
892
893
894\subsection{Routine Prototype}
895
896The syntax of the new routine prototype declaration follows directly from the new routine definition syntax;
897as well, parameter names are optional, e.g.:
898\begin{lstlisting}
899[ int x ] f ();                                 §\C{// returning int with no parameters}§
900[ * int ] g (int y);                    §\C{// returning pointer to int with int parameter}§
901[ ] h (int,char);                               §\C{// returning no result with int and char parameters}§
902[ * int,int ] j (int);                  §\C{// returning pointer to int and int, with int parameter}§
903\end{lstlisting}
904This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa).
905It is possible to declare multiple routine-prototypes in a single declaration, but the entire type specification is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), e.g.:
906\begin{quote2}
907\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
908\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
909\begin{lstlisting}
910[ int ] f(int), g;
911\end{lstlisting}
912&
913\begin{lstlisting}
914int f(int), g(int);
915\end{lstlisting}
916\end{tabular}
917\end{quote2}
918Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} e.g.:
919\begin{lstlisting}
920extern [ int ] f (int);
921static [ int ] g (int);
922\end{lstlisting}
923
924
925\section{Routine Pointers}
926
927The syntax for pointers to \CFA routines specifies the pointer name on the right, e.g.:
928\begin{lstlisting}
929* [ int x ] () fp;                      §\C{// pointer to routine returning int with no parameters}§
930* [ * int ] (int y) gp;         §\C{// pointer to routine returning pointer to int with int parameter}§
931* [ ] (int,char) hp;            §\C{// pointer to routine returning no result with int and char parameters}§
932* [ * int,int ] (int) jp;       §\C{// pointer to routine returning pointer to int and int, with int parameter}§
933\end{lstlisting}
934While parameter names are optional, \emph{a routine name cannot be specified};
935for example, the following is incorrect:
936\begin{lstlisting}
937* [ int x ] f () fp;            §\C{// routine name "f" is not allowed}§
938\end{lstlisting}
939
940
941\section{Named and Default Arguments}
942
943Named and default arguments~\cite{Hardgrave76}\footnote{
944Francez~\cite{Francez77} proposed a further extension to the named-parameter passing style, which specifies what type of communication (by value, by reference, by name) the argument is passed to the routine.}
945are two mechanisms to simplify routine call.
946Both mechanisms are discussed with respect to \CFA.
947\begin{description}
948\item[Named (or Keyword) Arguments:]
949provide the ability to specify an argument to a routine call using the parameter name rather than the position of the parameter.
950For example, given the routine:
951\begin{lstlisting}
952void p( int x, int y, int z ) {...}
953\end{lstlisting}
954a positional call is:
955\begin{lstlisting}
956p( 4, 7, 3 );
957\end{lstlisting}
958whereas a named (keyword) call may be:
959\begin{lstlisting}
960p( z : 3, x : 4, y : 7 );       §\C{// rewrite $\Rightarrow$ p( 4, 7, 3 )}§
961\end{lstlisting}
962Here the order of the arguments is unimportant, and the names of the parameters are used to associate argument values with the corresponding parameters.
963The compiler rewrites a named call into a positional call.
964The advantages of named parameters are:
965\begin{itemize}
966\item
967Remembering the names of the parameters may be easier than the order in the routine definition.
968\item
969Parameter names provide documentation at the call site (assuming the names are descriptive).
970\item
971Changes can be made to the order or number of parameters without affecting the call (although the call must still be recompiled).
972\end{itemize}
973
974Unfortunately, named arguments do not work in C-style programming-languages because a routine prototype is not required to specify parameter names, nor do the names in the prototype have to match with the actual definition.
975For example, the following routine prototypes and definition are all valid.
976\begin{lstlisting}
977void p( int, int, int );                        §\C{// equivalent prototypes}§
978void p( int x, int y, int z );
979void p( int y, int x, int z );
980void p( int z, int y, int x );
981void p( int q, int r, int s ) {}        §\C{// match with this definition}§
982\end{lstlisting}
983Forcing matching parameter names in routine prototypes with corresponding routine definitions is possible, but goes against a strong tradition in C programming.
984Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports.
985The former is easy to do, while the latter is more complex.
986Currently, \CFA does \emph{not} attempt to support named arguments.
987
988\item[Default Arguments]
989provide the ability to associate a default value with a parameter so it can be optionally specified in the argument list.
990For example, given the routine:
991\begin{lstlisting}
992void p( int x = 1, int y = 2, int z = 3 ) {...}
993\end{lstlisting}
994the allowable positional calls are:
995\begin{lstlisting}
996p();                            §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
997p( 4 );                         §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
998p( 4, 4 );                      §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
999p( 4, 4, 4 );           §\C{// rewrite $\Rightarrow$ p( 4, 4, 4 )}§
1000// empty arguments
1001p(  , 4, 4 );           §\C{// rewrite $\Rightarrow$ p( 1, 4, 4 )}§
1002p( 4,  , 4 );           §\C{// rewrite $\Rightarrow$ p( 4, 2, 4 )}§
1003p( 4, 4,   );           §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§
1004p( 4,  ,   );           §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§
1005p(  , 4,   );           §\C{// rewrite $\Rightarrow$ p( 1, 4, 3 )}§
1006p(  ,  , 4 );           §\C{// rewrite $\Rightarrow$ p( 1, 2, 4 )}§
1007p(  ,  ,   );           §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§
1008\end{lstlisting}
1009Here the missing arguments are inserted from the default values in the parameter list.
1010The compiler rewrites missing default values into explicit positional arguments.
1011The advantages of default values are:
1012\begin{itemize}
1013\item
1014Routines with a large number of parameters are often very generalized, giving a programmer a number of different options on how a computation is performed.
1015For many of these kinds of routines, there are standard or default settings that work for the majority of computations.
1016Without default values for parameters, a programmer is forced to specify these common values all the time, resulting in long argument lists that are error prone.
1017\item
1018When a routine's interface is augmented with new parameters, it extends the interface providing generalizability\footnote{
1019``It should be possible for the implementor of an abstraction to increase its generality.
1020So long as the modified abstraction is a generalization of the original, existing uses of the abstraction will not require change.
1021It might be possible to modify an abstraction in a manner which is not a generalization without affecting existing uses, but, without inspecting the modules in which the uses occur, this possibility cannot be determined.
1022This criterion precludes the addition of parameters, unless these parameters have default or inferred values that are valid for all possible existing applications.''~\cite[p.~128]{Cormack90}}
1023(somewhat like the generalization provided by inheritance for classes).
1024That is, all existing calls are still valid, although the call must still be recompiled.
1025\end{itemize}
1026The only disadvantage of default arguments is that unintentional omission of an argument may not result in a compiler-time error.
1027Instead, a default value is used, which may not be the programmer's intent.
1028
1029Default values may only appear in a prototype versus definition context:
1030\begin{lstlisting}
1031void p( int x, int y = 2, int z = 3 );          §\C{// prototype: allowed}§
1032void p( int, int = 2, int = 3 );                        §\C{// prototype: allowed}§
1033void p( int x, int y = 2, int z = 3 ) {}        §\C{// definition: not allowed}§
1034\end{lstlisting}
1035The reason for this restriction is to allow separate compilation.
1036Multiple prototypes with different default values is an error.
1037\end{description}
1038
1039Ellipse (``...'') arguments present problems when used with default arguments.
1040The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities:
1041\begin{lstlisting}
1042p( /* positional */, . . ., /* named */ );
1043p( /* positional */, /* named */, . . . );
1044\end{lstlisting}
1045While it is possible to implement both approaches, the first possibly is more complex than the second, e.g.:
1046\begin{lstlisting}
1047p( int x, int y, int z, . . . );
1048p( 1, 4, 5, 6, z : 3, y : 2 ); §\C{// assume p( /* positional */, . . ., /* named */ );}§
1049p( 1, z : 3, y : 2, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, . . . );}§
1050\end{lstlisting}
1051In the first call, it is necessary for the programmer to conceptually rewrite the call, changing named arguments into positional, before knowing where the ellipse arguments begin.
1052Hence, this approach seems significantly more difficult, and hence, confusing and error prone.
1053In the second call, the named arguments separate the positional and ellipse arguments, making it trivial to read the call.
1054
1055The problem is exacerbated with default arguments, e.g.:
1056\begin{lstlisting}
1057void p( int x, int y = 2, int z = 3. . . );
1058p( 1, 4, 5, 6, z : 3 );         §\C{// assume p( /* positional */, . . ., /* named */ );}§
1059p( 1, z : 3, 4, 5, 6 );         §\C{// assume p( /* positional */, /* named */, . . . );}§
1060\end{lstlisting}
1061The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments;
1062therefore, argument 5 subsequently conflicts with the named argument z : 3.
1063In the second call, the default value for y is implicitly inserted after argument 1 and the named arguments separate the positional and ellipse arguments, making it trivial to read the call.
1064For these reasons, \CFA requires named arguments before ellipse arguments.
1065Finally, while ellipse arguments are needed for a small set of existing C routines, like printf, the extended \CFA type system largely eliminates the need for ellipse arguments (see Section 24), making much of this discussion moot.
1066
1067Default arguments and overloading (see Section 24) are complementary.
1068While in theory default arguments can be simulated with overloading, as in:
1069\begin{quote2}
1070\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1071\multicolumn{1}{c@{\hspace{3em}}}{\textbf{default arguments}}   & \multicolumn{1}{c}{\textbf{overloading}}      \\
1072\begin{lstlisting}
1073void p( int x, int y = 2, int z = 3 ) {...}
1074
1075
1076\end{lstlisting}
1077&
1078\begin{lstlisting}
1079void p( int x, int y, int z ) {...}
1080void p( int x ) { p( x, 2, 3 ); }
1081void p( int x, int y ) { p( x, y, 3 ); }
1082\end{lstlisting}
1083\end{tabular}
1084\end{quote2}
1085the number of required overloaded routines is linear in the number of default values, which is unacceptable growth.
1086In general, overloading should only be used over default arguments if the body of the routine is significantly different.
1087Furthermore, overloading cannot handle accessing default arguments in the middle of a positional list, via a missing argument, such as:
1088\begin{lstlisting}
1089p( 1, /* default */, 5 );               §\C{// rewrite $\Rightarrow$ p( 1, 2, 5 )}§
1090\end{lstlisting}
1091
1092Given the \CFA restrictions above, both named and default arguments are backwards compatible.
1093\Index*[C++]{\CC} only supports default arguments;
1094\Index*{Ada} supports both named and default arguments.
1095
1096
1097\section{Type/Routine Nesting}
1098
1099Nesting of types and routines is useful for controlling name visibility (\newterm{name hiding}).
1100
1101
1102\subsection{Type Nesting}
1103
1104\CFA allows \Index{type nesting}, and type qualification of the nested types (see \VRef[Figure]{f:TypeNestingQualification}), where as C hoists\index{type hoisting} (refactors) nested types into the enclosing scope and has no type qualification.
1105\begin{figure}
1106\begin{tabular}{@{}l@{\hspace{3em}}l|l@{}}
1107\multicolumn{1}{c@{\hspace{3em}}}{\textbf{C Type Nesting}}      & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}}      & \multicolumn{1}{|c}{\textbf{\CFA}}    \\
1108\hline
1109\begin{lstlisting}
1110struct S {
1111        enum C { R, G, B };
1112        struct T {
1113                union U { int i, j; };
1114                enum C c;
1115                short int i, j;
1116        };
1117        struct T t;
1118} s;
1119
1120int fred() {
1121        s.t.c = R;
1122        struct T t = { R, 1, 2 };
1123        enum C c;
1124        union U u;
1125}
1126\end{lstlisting}
1127&
1128\begin{lstlisting}
1129enum C { R, G, B };
1130union U { int i, j; };
1131struct T {
1132        enum C c;
1133        short int i, j;
1134};
1135struct S {
1136        struct T t;
1137} s;
1138       
1139
1140
1141
1142
1143
1144
1145\end{lstlisting}
1146&
1147\begin{lstlisting}
1148struct S {
1149        enum C { R, G, B };
1150        struct T {
1151                union U { int i, j; };
1152                enum C c;
1153                short int i, j;
1154        };
1155        struct T t;
1156} s;
1157
1158int fred() {
1159        s.t.c = ®S.®R;  // type qualification
1160        struct ®S.®T t = { ®S.®R, 1, 2 };
1161        enum ®S.®C c;
1162        union ®S.T.®U u;
1163}
1164\end{lstlisting}
1165\end{tabular}
1166\caption{Type Nesting / Qualification}
1167\label{f:TypeNestingQualification}
1168\end{figure}
1169In the left example in C, types ©C©, ©U© and ©T© are implicitly hoisted outside of type ©S© into the containing block scope.
1170In the right example in \CFA, the types are not hoisted and accessed using the field-selection operator ``©.©'' for type qualification, as does \Index*{Java}, rather than the \CC type-selection operator ``©::©''.
1171
1172
1173\subsection{Routine Nesting}
1174
1175While \CFA does not provide object programming by putting routines into structures, it does rely heavily on locally nested routines to redefine operations at or close to a call site.
1176For example, the C quick-sort is wrapped into the following polymorphic \CFA routine:
1177\begin{lstlisting}
1178forall( otype T | { int ?<?( T, T ); } )
1179void qsort( const T * arr, size_t dimension );
1180\end{lstlisting}
1181which can be used to sort in ascending and descending order by locally redefining the less-than operator into greater-than.
1182\begin{lstlisting}
1183const unsigned int size = 5;
1184int ia[size];
1185...                                             §\C{// assign values to array ia}§
1186qsort( ia, size );              §\C{// sort ascending order using builtin ?<?}§
1187{
1188        ®int ?<?( int x, int y ) { return x > y; }® §\C{// nested routine}§
1189        qsort( ia, size );      §\C{// sort descending order by local redefinition}§
1190}
1191\end{lstlisting}
1192
1193Nested routines are not first-class, meaning a nested routine cannot be returned if it has references to variables in its enclosing blocks;
1194the only exception is references to the external block of the translation unit, as these variables persist for the duration of the program.
1195The following program in undefined in \CFA (and Indexc{gcc})
1196\begin{lstlisting}
1197[* [int]( int )] foo() {                §\C{// int (*foo())( int )}§
1198        int ®i® = 7;
1199        int bar( int p ) {
1200                ®i® += 1;                               §\C{// dependent on local variable}§
1201                sout | ®i® | endl;
1202        }
1203        return bar;                                     §\C{// undefined because of local dependence}§
1204}
1205int main() {
1206        * [int](int) fp = foo();        §\C{// int (*fp)(int)}§
1207    sout | fp( 3 ) | endl;
1208}
1209\end{lstlisting}
1210because
1211
1212Currently, there are no \Index{lambda} expressions, i.e., unnamed routines because routine names are very important to properly select the correct routine.
1213
1214
1215\section{Lexical List}
1216
1217In C and \CFA, lists of elements appear in several contexts, such as the parameter list for a routine call.
1218(More contexts are added shortly.)
1219A list of such elements is called a \newterm{lexical list}.
1220The general syntax of a lexical list is:
1221\begin{lstlisting}
1222[ §\emph{exprlist}§ ]
1223\end{lstlisting}
1224where ©$\emph{exprlist}$© is a list of one or more expressions separated by commas.
1225The brackets, ©[]©, allow differentiating between lexical lists and expressions containing the C comma operator.
1226The following are examples of lexical lists:
1227\begin{lstlisting}
1228[ x, y, z ]
1229[ 2 ]
1230[ v+w, x*y, 3.14159, f() ]
1231\end{lstlisting}
1232Tuples are permitted to contain sub-tuples (i.e., nesting), such as ©[ [ 14, 21 ], 9 ]©, which is a 2-element tuple whose first element is itself a tuple.
1233Note, a tuple is not a record (structure);
1234a record denotes a single value with substructure, whereas a tuple is multiple values with no substructure (see flattening coercion in Section 12.1).
1235In essence, tuples are largely a compile time phenomenon, having little or no runtime presence.
1236
1237Tuples can be organized into compile-time tuple variables;
1238these variables are of \newterm{tuple type}.
1239Tuple variables and types can be used anywhere lists of conventional variables and types can be used.
1240The general syntax of a tuple type is:
1241\begin{lstlisting}
1242[ §\emph{typelist}§ ]
1243\end{lstlisting}
1244where ©$\emph{typelist}$© is a list of one or more legal \CFA or C type specifications separated by commas, which may include other tuple type specifications.
1245Examples of tuple types include:
1246\begin{lstlisting}
1247[ unsigned int, char ]
1248[ double, double, double ]
1249[ * int, int * ]                §\C{// mix of CFA and ANSI}§
1250[ * [ 5 ] int, * * char, * [ [ int, int ] ] (int, int) ]
1251\end{lstlisting}
1252Like tuples, tuple types may be nested, such as ©[ [ int, int ], int ]©, which is a 2-element tuple type whose first element is itself a tuple type.
1253
1254Examples of declarations using tuple types are:
1255\begin{lstlisting}
1256[ int, int ] x;                 §\C{// 2 element tuple, each element of type int}§
1257* [ char, char ] y;             §\C{// pointer to a 2 element tuple}§
1258[ [ int, int ] ] z ([ int, int ]);
1259\end{lstlisting}
1260The last example declares an external routine that expects a 2 element tuple as an input parameter and returns a 2 element tuple as its result.
1261
1262As mentioned, tuples can appear in contexts requiring a list of value, such as an argument list of a routine call.
1263In unambiguous situations, the tuple brackets may be omitted, e.g., a tuple that appears as an argument may have its
1264square brackets omitted for convenience; therefore, the following routine invocations are equivalent:
1265\begin{lstlisting}
1266f( [ 1, x+2, fred() ] );
1267f( 1, x+2, fred() );
1268\end{lstlisting}
1269Also, a tuple or a tuple variable may be used to supply all or part of an argument list for a routine expecting multiple input parameters or for a routine expecting a tuple as an input parameter.
1270For example, the following are all legal:
1271\begin{lstlisting}
1272[ int, int ] w1;
1273[ int, int, int ] w2;
1274[ void ] f (int, int, int); /* three input parameters of type int */
1275[ void ] g ([ int, int, int ]); /* 3 element tuple as input */
1276f( [ 1, 2, 3 ] );
1277f( w1, 3 );
1278f( 1, w1 );
1279f( w2 );
1280g( [ 1, 2, 3 ] );
1281g( w1, 3 );
1282g( 1, w1 );
1283g( w2 );
1284\end{lstlisting}
1285Note, in all cases 3 arguments are supplied even though the syntax may appear to supply less than 3. As mentioned, a
1286tuple does not have structure like a record; a tuple is simply converted into a list of components.
1287\begin{rationale}
1288The present implementation of \CFA does not support nested routine calls when the inner routine returns multiple values; i.e., a statement such as ©g( f() )© is not supported.
1289Using a temporary variable to store the  results of the inner routine and then passing this variable to the outer routine works, however.
1290\end{rationale}
1291
1292A tuple can contain a C comma expression, provided the expression containing the comma operator is enclosed in parentheses.
1293For instance, the following tuples are equivalent:
1294\begin{lstlisting}
1295[ 1, 3, 5 ]
1296[ 1, (2, 3), 5 ]
1297\end{lstlisting}
1298The second element of the second tuple is the expression (2, 3), which yields the result 3.
1299This requirement is the same as for comma expressions in argument lists.
1300
1301Type qualifiers, i.e., const and volatile, may modify a tuple type.
1302The meaning is the same as for a type qualifier modifying an aggregate type [Int99, x 6.5.2.3(7),x 6.7.3(11)], i.e., the qualifier is distributed across all of the types in the tuple, e.g.:
1303\begin{lstlisting}
1304const volatile [ int, float, const int ] x;
1305\end{lstlisting}
1306is equivalent to:
1307\begin{lstlisting}
1308[ const volatile int, const volatile float, const volatile int ] x;
1309\end{lstlisting}
1310Declaration qualifiers can only appear at the start of a \CFA tuple declaration4, e.g.:
1311\begin{lstlisting}
1312extern [ int, int ] w1;
1313static [ int, int, int ] w2;
1314\end{lstlisting}
1315\begin{rationale}
1316Unfortunately, C's syntax for subscripts precluded treating them as tuples.
1317The C subscript list has the form ©[i][j]...© and not ©[i, j, ...]©.
1318Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, e.g., ©f[g()]© always means a single subscript value because there is only one set of brackets.
1319Fixing this requires a major change to C because the syntactic form ©M[i, j, k]© already has a particular meaning: ©i, j, k© is a comma expression.
1320\end{rationale}
1321
1322
1323\subsection{Tuple Coercions}
1324
1325There are four coercions that can be performed on tuples and tuple variables: closing, opening, flattening and structuring.
1326In addition, the coercion of dereferencing can be performed on a tuple variable to yield its value(s), as for other variables.
1327A \newterm{closing coercion} takes a set of values and converts it into a tuple value, which is a contiguous set of values, as in:
1328\begin{lstlisting}
1329[ int, int, int, int ] w;
1330w = [ 1, 2, 3, 4 ];
1331\end{lstlisting}
1332First the right-hand tuple is closed into a tuple value and then the tuple value is assigned.
1333
1334An \newterm{opening coercion} is the opposite of closing; a tuple value is converted into a tuple of values, as in:
1335\begin{lstlisting}
1336[ a, b, c, d ] = w
1337\end{lstlisting}
1338©w© is implicitly opened to yield a tuple of four values, which are then assigned individually.
1339
1340A \newterm{flattening coercion} coerces a nested tuple, i.e., a tuple with one or more components, which are themselves tuples, into a flattened tuple, which is a tuple whose components are not tuples, as in:
1341\begin{lstlisting}
1342[ a, b, c, d ] = [ 1, [ 2, 3 ], 4 ];
1343\end{lstlisting}
1344First the right-hand tuple is flattened and then the values are assigned individually.
1345Flattening is also performed on tuple types.
1346For example, the type ©[ int, [ int, int ], int ]© can be coerced, using flattening, into the type ©[ int, int, int, int ]©.
1347
1348A \newterm{structuring coercion} is the opposite of flattening;
1349a tuple is structured into a more complex nested tuple.
1350For example, structuring the tuple ©[ 1, 2, 3, 4 ]© into the tuple ©[ 1, [ 2, 3 ], 4 ]© or the tuple type ©[ int, int, int, int ]© into the tuple type ©[ int, [ int, int ], int ]©.
1351In the following example, the last assignment illustrates all the tuple coercions:
1352\begin{lstlisting}
1353[ int, int, int, int ] w = [ 1, 2, 3, 4 ];
1354int x = 5;
1355[ x, w ] = [ w, x ];            §\C{// all four tuple coercions}§
1356\end{lstlisting}
1357Starting on the right-hand tuple in the last assignment statement, w is opened, producing a tuple of four values;
1358therefore, the right-hand tuple is now the tuple ©[ [ 1, 2, 3, 4 ], 5 ]©.
1359This tuple is then flattened, yielding ©[ 1, 2, 3, 4, 5 ]©, which is structured into ©[ 1, [ 2, 3, 4, 5 ] ]© to match the tuple type of the left-hand side.
1360The tuple ©[ 2, 3, 4, 5 ]© is then closed to create a tuple value.
1361Finally, ©x© is assigned ©1© and ©w© is assigned the tuple value using multiple assignment (see Section 14).
1362\begin{rationale}
1363A possible additional language extension is to use the structuring coercion for tuples to initialize a complex record with a tuple.
1364\end{rationale}
1365
1366
1367\section{Mass Assignment}
1368
1369\CFA permits assignment to several variables at once using mass assignment~\cite{CLU}.
1370Mass assignment has the following form:
1371\begin{lstlisting}
1372[ §\emph{lvalue}§, ..., §\emph{lvalue}§ ] = §\emph{expr}§;
1373\end{lstlisting}
1374\index{lvalue}
1375The left-hand side is a tuple of \emph{lvalues}, which is a list of expressions each yielding an address, i.e., any data object that can appear on the left-hand side of a conventional assignment statement.
1376©$\emph{expr}$© is any standard arithmetic expression.
1377Clearly, the types of the entities being assigned must be type compatible with the value of the expression.
1378
1379Mass assignment has parallel semantics, e.g., the statement:
1380\begin{lstlisting}
1381[ x, y, z ] = 1.5;
1382\end{lstlisting}
1383is equivalent to:
1384\begin{lstlisting}
1385x = 1.5; y = 1.5; z = 1.5;
1386\end{lstlisting}
1387This semantics is not the same as the following in C:
1388\begin{lstlisting}
1389x = y = z = 1.5;
1390\end{lstlisting}
1391as conversions between intermediate assignments may lose information.
1392A more complex example is:
1393\begin{lstlisting}
1394[ i, y[i], z ] = a + b;
1395\end{lstlisting}
1396which is equivalent to:
1397\begin{lstlisting}
1398t = a + b;
1399a1 = &i; a2 = &y[i]; a3 = &z;
1400*a1 = t; *a2 = t; *a3 = t;
1401\end{lstlisting}
1402The temporary ©t© is necessary to store the value of the expression to eliminate conversion issues.
1403The temporaries for the addresses are needed so that locations on the left-hand side do not change as the values are assigned.
1404In this case, ©y[i]© uses the previous value of ©i© and not the new value set at the beginning of the mass assignment.
1405
1406
1407\section{Multiple Assignment}
1408
1409\CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}.
1410Multiple assignment has the following form:
1411\begin{lstlisting}
1412[ §\emph{lvalue}§, . . ., §\emph{lvalue}§ ] = [ §\emph{expr}§, . . ., §\emph{expr}§ ];
1413\end{lstlisting}
1414\index{lvalue}
1415The left-hand side is a tuple of \emph{lvalues}, and the right-hand side is a tuple of \emph{expr}s.
1416Each \emph{expr} appearing on the righthand side of a multiple assignment statement is assigned to the corresponding \emph{lvalues} on the left-hand side of the statement using parallel semantics for each assignment.
1417An example of multiple assignment is:
1418\begin{lstlisting}
1419[ x, y, z ] = [ 1, 2, 3 ];
1420\end{lstlisting}
1421Here, the values ©1©, ©2© and ©3© are assigned, respectively, to the variables ©x©, ©y© and ©z©.
1422 A more complex example is:
1423\begin{lstlisting}
1424[ i, y[ i ], z ] = [ 1, i, a + b ];
1425\end{lstlisting}
1426Here, the values ©1©, ©i© and ©a + b© are assigned to the variables ©i©, ©y[i]© and ©z©, respectively.
1427 Note, the parallel semantics of
1428multiple assignment ensures:
1429\begin{lstlisting}
1430[ x, y ] = [ y, x ];
1431\end{lstlisting}
1432correctly interchanges (swaps) the values stored in ©x© and ©y©.
1433The following cases are errors:
1434\begin{lstlisting}
1435[ a, b, c ] = [ 1, 2, 3, 4 ];
1436[ a, b, c ] = [ 1, 2 ];
1437\end{lstlisting}
1438because the number of entities in the left-hand tuple is unequal with the right-hand tuple.
1439
1440As for all tuple contexts in C, side effects should not be used because C does not define an ordering for the evaluation of the elements of a tuple;
1441both these examples produce indeterminate results:
1442\begin{lstlisting}
1443f( x++, x++ );                          §\C{// C routine call with side effects in arguments}§
1444[ v1, v2 ] = [ x++, x++ ];      §\C{// side effects in righthand side of multiple assignment}§
1445\end{lstlisting}
1446
1447
1448\section{Cascade Assignment}
1449
1450As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment.
1451Cascade assignment has the following form:
1452\begin{lstlisting}
1453§\emph{tuple}§ = §\emph{tuple}§ = ... = §\emph{tuple}§;
1454\end{lstlisting}
1455and it has the same parallel semantics as for mass and multiple assignment.
1456Some examples of cascade assignment are:
1457\begin{lstlisting}
1458x1 = y1 = x2 = y2 = 0;
1459[ x1, y1 ] = [ x2, y2 ] = [ x3, y3 ];
1460[ x1, y1 ] = [ x2, y2 ] = 0;
1461[ x1, y1 ] = z = 0;
1462\end{lstlisting}
1463As in C, the rightmost assignment is performed first, i.e., assignment parses right to left.
1464
1465
1466\section{Unnamed Structure Fields}
1467
1468C requires each field of a structure to have a name, except for a bit field associated with a basic type, e.g.:
1469\begin{lstlisting}
1470struct {
1471        int f1;                 // named field
1472        int f2 : 4;             // named field with bit field size
1473        int : 3;                // unnamed field for basic type with bit field size
1474        int ;                   // disallowed, unnamed field
1475        int *;                  // disallowed, unnamed field
1476        int (*)(int);   // disallowed, unnamed field
1477};
1478\end{lstlisting}
1479This requirement is relaxed by making the field name optional for all field declarations; therefore, all the field declarations in the example are allowed.
1480As for unnamed bit fields, an unnamed field is used for padding a structure to a particular size.
1481A list of unnamed fields is also supported, e.g.:
1482\begin{lstlisting}
1483struct {
1484        int , , ;               // 3 unnamed fields
1485}
1486\end{lstlisting}
1487
1488
1489\section{Field Tuples}
1490
1491Tuples may be used to select multiple fields of a record by field name.
1492Its general form is:
1493\begin{lstlisting}
1494§\emph{expr}§ . [ §\emph{fieldlist}§ ]
1495§\emph{expr}§ -> [ §\emph{fieldlist}§ ]
1496\end{lstlisting}
1497\emph{expr} is any expression yielding a value of type record, e.g., ©struct©, ©union©.
1498Each element of \emph{ fieldlist} is an element of the record specified by \emph{expr}.
1499A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is
1500the following:
1501\begin{lstlisting}
1502struct s {
1503        int f1, f2;
1504        char f3;
1505        double f4;
1506} v;
1507v.[ f3, f1, f2 ] = ['x', 11, 17 ];      §\C{// equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17}§
1508f( v.[ f3, f1, f2 ] );                          §\C{// equivalent to f( v.f3, v.f1, v.f2 )}§
1509\end{lstlisting}
1510Note, the fields appearing in a record-field tuple may be specified in any order;
1511also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple.
1512
1513If a field of a ©struct© is itself another ©struct©, multiple fields of this subrecord can be specified using a nested record-field tuple, as in the following example:
1514\begin{lstlisting}
1515struct inner {
1516        int f2, f3;
1517};
1518struct outer {
1519        int f1;
1520        struct inner i;
1521        double f4;
1522} o;
1523
1524o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ];
1525\end{lstlisting}
1526
1527
1528\section{Labelled Continue / Break}
1529
1530While C provides ©continue© and ©break© statements for altering control flow, both are restricted to one level of nesting for a particular control structure.
1531Unfortunately, this restriction forces programmers to use ©goto© to achieve the equivalent control-flow for more than one level of nesting.
1532To prevent having to switch to the ©goto©, \CFA extends the ©continue©\index{continue@©continue©}\index{continue@©continue©!labelled}\index{labelled!continue@©continue©} and ©break©\index{break@©break©}\index{break@©break©!labelled}\index{labelled!break@©break©} with a target label to support static multi-level exit\index{multi-level exit}\index{static multi-level exit}~\cite{Buhr85,Java}.
1533For both ©continue© and ©break©, the target label must be directly associated with a ©for©, ©while© or ©do© statement;
1534for ©break©, the target label can also be associated with a ©switch©, ©if© or compound (©{}©) statement.
1535
1536The following example shows the labelled ©continue© specifying which control structure is the target for the next loop iteration:
1537\begin{quote2}
1538\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1539\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1540\begin{lstlisting}
1541®L1:® do {
1542        ®L2:® while ( ... ) {
1543                ®L3:® for ( ... ) {
1544                        ... continue ®L1®; ...  // continue do
1545                        ... continue ®L2®; ...  // continue while
1546                        ... continue ®L3®; ...  // continue for
1547                } // for
1548        } // while
1549} while ( ... );
1550\end{lstlisting}
1551&
1552\begin{lstlisting}
1553do {
1554        while ( ... ) {
1555                for ( ... ) {
1556                        ... goto L1; ...
1557                        ... goto L2; ...
1558                        ... goto L3; ...
1559                L3: ; }
1560        L2: ; }
1561L1: ; } while ( ... );
1562\end{lstlisting}
1563\end{tabular}
1564\end{quote2}
1565The innermost loop has three restart points, which cause the next loop iteration to begin.
1566
1567The following example shows the labelled ©break© specifying which control structure is the target for exit:
1568\begin{quote2}
1569\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
1570\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{C}}        \\
1571\begin{lstlisting}
1572®L1:® {
1573        ... §declarations§ ...
1574        ®L2:® switch ( ... ) {
1575          case 3:
1576            ®L3:® if ( ... ) {
1577                        ®L4:® for ( ... ) {
1578                                ... break ®L1®; ...     // exit compound statement
1579                                ... break ®L2®; ...     // exit switch
1580                                ... break ®L3®; ...     // exit if
1581                                ... break ®L4®; ...     // exit loop
1582                        } // for
1583                } else {
1584                        ... break ®L3®; ...             // exit if
1585                } // if
1586        } // switch
1587} // compound
1588\end{lstlisting}
1589&
1590\begin{lstlisting}
1591{
1592        ... §declarations§ ...
1593        switch ( ... ) {
1594          case 3:
1595            if ( ... ) {
1596                        for ( ... ) {
1597                                ... goto L1; ...
1598                                ... goto L2; ...
1599                                ... goto L3; ...
1600                                ... goto L4; ...
1601                        } L4: ;
1602                } else {
1603                        ... goto L3; ...
1604                } L3: ;
1605        } L2: ;
1606} L1: ;
1607\end{lstlisting}
1608\end{tabular}
1609\end{quote2}
1610The innermost loop has four exit points, which cause termination of one or more of the four \Index{nested control structure}s.
1611
1612Both ©continue© and ©break© with target labels are simply a ©goto©\index{goto@©goto©!restricted} restricted in the following ways:
1613\begin{itemize}
1614\item
1615They cannot be used to create a loop.
1616This means that only the looping construct can be used to create a loop.
1617This restriction is important since all situations that can result in repeated execution of statements in a program are clearly delineated.
1618\item
1619Since they always transfer out of containing control structures, they cannot be used to branch into a control structure.
1620\end{itemize}
1621The advantage of the labelled ©continue©/©break© is allowing static multi-level exits without having to use the ©goto© statement and tying control flow to the target control structure rather than an arbitrary point in a program.
1622Furthermore, the location of the label at the \emph{beginning} of the target control structure informs the reader that complex control-flow is occurring in the body of the control structure.
1623With ©goto©, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader.
1624Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs.
1625The implicit targets of the current ©continue© and ©break©, i.e., the closest enclosing loop or ©switch©, change as certain constructs are added or removed.
1626
1627
1628\section{Switch Statement}
1629
1630C allows a number of questionable forms for the ©switch© statement:
1631\begin{enumerate}
1632\item
1633By default, the end of a ©case© clause\footnote{
1634In this section, the term \emph{case clause} refers to either a ©case© or ©default© clause.}
1635\emph{falls through} to the next ©case© clause in the ©switch© statement;
1636to exit a ©switch© statement from a ©case© clause requires explicitly terminating the clause with a transfer statement, most commonly ©break©:
1637\begin{lstlisting}
1638switch ( i ) {
1639  case 1:
1640        ...
1641        // fall-through
1642  case 2:
1643        ...
1644        break;  // exit switch statement
1645}
1646\end{lstlisting}
1647The ability to fall-through to the next clause \emph{is} a useful form of control flow, specifically when a sequence of case actions compound:
1648\begin{lstlisting}
1649switch ( argc ) {
1650  case 3:
1651        // open output file
1652        // fall-through
1653  case 2:
1654        // open input file
1655        break;  // exit switch statement
1656  default:
1657        // usage message
1658}
1659\end{lstlisting}
1660In this example, case 2 is always done if case 3 is done.
1661This control flow is difficult to simulate with if statements or a ©switch© statement without fall-through as code must be duplicated or placed in a separate routine.
1662C also uses fall-through to handle multiple case-values resulting in the same action:
1663\begin{lstlisting}
1664switch ( i ) {
1665  case 1: case 3: case 5:       // odd values
1666        // same action
1667        break;
1668  case 2: case 4: case 6:       // even values
1669        // same action
1670        break;
1671}
1672\end{lstlisting}
1673However, this situation is handled in other languages without fall-through by allowing a list of case values.
1674While fall-through itself is not a problem, the problem occurs when fall-through is the default, as this semantics is not intuitive to most programmers and is different from virtually all other programming languages with a ©switch© statement.
1675Hence, default fall-through semantics results in a large number of programming errors as programmers often forget the ©break© statement at the end of a ©case© clause, resulting in inadvertent fall-through.
1676
1677\item
1678It is possible to place ©case© clauses on statements nested \emph{within} the body of the ©switch© statement:
1679\begin{lstlisting}
1680switch ( i ) {
1681  case 0:
1682        if ( j < k ) {
1683                ...
1684          case 1:               // transfer into "if" statement
1685                if ( j < m ) {
1686                        ...
1687                  case 2:       // transfer into "if" statement
1688                        ...
1689                }
1690        }
1691  case 3:
1692        while ( j < 5 ) {
1693                ...
1694          case 4:               // transfer into "while" statement
1695                ...
1696        }
1697}
1698\end{lstlisting}
1699The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties.
1700The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it.
1701The technical problem results from the inability to ensure allocation and initialization of variables when blocks are not entered at the beginning.
1702Often transferring into a block can bypass variable declaration and/or its initialization, which results in subsequent errors.
1703There are virtually no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it.
1704Nevertheless, C does have an idiom where this capability is used, known as ``\Index*{Duff's device}''~\cite{Duff83}:
1705\begin{lstlisting}
1706register int n = (count + 7) / 8;
1707switch ( count % 8 ) {
1708case 0: do{ *to = *from++;
1709case 7:         *to = *from++;
1710case 6:         *to = *from++;
1711case 5:         *to = *from++;
1712case 4:         *to = *from++;
1713case 3:         *to = *from++;
1714case 2:         *to = *from++;
1715case 1:         *to = *from++;
1716                } while ( --n > 0 );
1717}
1718\end{lstlisting}
1719which unrolls a loop N times (N = 8 above) and uses the ©switch© statement to deal with any iterations not a multiple of N.
1720While efficient, this sort of special purpose usage is questionable:
1721\begin{quote}
1722Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this
1723discovery.~\cite{Duff83}
1724\end{quote}
1725\item
1726It is possible to place the ©default© clause anywhere in the list of labelled clauses for a ©switch© statement, rather than only at the end.
1727Virtually all programming languages with a ©switch© statement require the ©default© clause to appear last in the case-clause list.
1728The logic for this semantics is that after checking all the ©case© clauses without success, the ©default© clause is selected;
1729hence, physically placing the ©default© clause at the end of the ©case© clause list matches with this semantics.
1730This physical placement can be compared to the physical placement of an ©else© clause at the end of a series of connected ©if©/©else© statements.
1731
1732\item
1733It is possible to place unreachable code at the start of a ©switch© statement, as in:
1734\begin{lstlisting}
1735switch ( x ) {
1736        int y = 1;                      §\C{// unreachable initialization}§
1737        x = 7;                          §\C{// unreachable code}§
1738  case 3: ...
1739        y = 3;
1740        ...
1741}
1742\end{lstlisting}
1743While the declaration of the local variable ©y© is useful and its scope is across all ©case© clauses, the initialization for such a variable is defined to never be executed because control always transfers over it.
1744Furthermore, any statements before the first ©case© clause can only be executed if labelled and transfered to using a ©goto©, either from outside or inside of the ©switch©.
1745As mentioned, transfer into control structures should be forbidden.
1746Transfers from within the ©switch© body using a ©goto© are equally unpalatable.
1747\end{enumerate}
1748Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program:
1749\begin{itemize}
1750\item
1751the number of ©switch© statements is small,
1752\item
1753most ©switch© statements are well formed (i.e., no \Index*{Duff's device}),
1754\item
1755the ©default© clause is usually written as the last case-clause,
1756\item
1757and there is only a medium amount of fall-through from one ©case© clause to the next, and most of these result from a list of case values executing common code, rather than a sequence of case actions that compound.
1758\end{itemize}
1759These observations help to put the effects of suggested changes into perspective.
1760\begin{enumerate}
1761\item
1762Eliminating default fall-through has the greatest potential for affecting existing code.
1763However, even if fall-through is removed, most ©switch© statements would continue to work because of the explicit transfers already present at the end of each ©case© clause, the common placement of the ©default© clause at the end of the case list, and the most common use of fall-through, i.e., a list of ©case© clauses executing common code, e.g.:
1764\begin{lstlisting}
1765case 1:  case 2:  case 3: ...
1766\end{lstlisting}
1767still work.
1768Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments.
1769Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called ©choose©, with no fall-through semantics.
1770The ©choose© statement is identical to the new ©switch© statement, except there is no implicit fall-through between case-clauses and the ©break© statement applies to the enclosing loop construct (as for the ©continue© statement in a ©switch© statement).
1771It is still possible to fall-through if a case-clause ends with the new keyword ©fallthru©, e.g.:
1772\begin{lstlisting}
1773®choose® ( i ) {
1774  case 3:
1775        ...
1776        ®fallthru®;             §\C{// explicit fall through}§
1777  case 5:
1778        ...                             §\C{// implicit end of switch}§
1779  case 7:
1780        ...
1781        ®break®                 §\C{// transfer to end of enclosing loop / switch}§
1782  default:
1783        j = 3;
1784}
1785\end{lstlisting}
1786The ability to fall-through is retained because it is a sufficient C-idiom that most C programmers simply expect it, and its absence might discourage these programmers from using the ©choose© statement.
1787\item
1788Eliminating \Index*{Duff's device} is straightforward and only invalidates a small amount of very questionable code.
1789The solution is to allow ©case© clauses to only appear at the same nesting level as the ©switch© body, as is done in most other programming languages with ©switch© statements.
1790\item
1791The issue of ©default© at locations other than at the end of the cause clause can be solved by using good programming style, and there are a few reasonable situations involving fall-through where the ©default© clause needs to appear is locations other than at the end.
1792Therefore, no language change is made for this issue.
1793\item
1794Dealing with unreachable code at the start of a ©switch© statement is solved by defining the declaration-list, including any associated initialization, at the start of a ©switch© statement body to be executed \emph{before} the transfer to the appropriate ©case© clause.
1795This semantics is the same as for declarations at the start of a loop body, which are executed before each iteration of the loop body.
1796As well, statements cannot appear before the first ©case© clause.
1797The change is compatible for declarations with initialization in this context because existing code cannot assume the initialization has occurred.
1798The change is incompatible for statements, but any existing code using it is highly questionable, as in:
1799\begin{lstlisting}
1800switch ( i ) {
1801        L: x = 5;               §\C{// questionable code}§
1802  case 0:
1803        ...
1804}
1805\end{lstlisting}
1806The statement after the ©switch© can never be executed unless it is labelled.
1807If it is labelled, it must be transfered to from outside or inside the ©switch© statement, neither of which is acceptable control flow.
1808\end{enumerate}
1809
1810
1811\section{Case Clause}
1812
1813C restricts the ©case© clause of a ©switch© statement to a single value.
1814For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values.
1815Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C.
1816Therefore, the ©case© clause is extended with a list of values, as in:
1817\begin{quote2}
1818\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1819\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
1820\begin{lstlisting}
1821switch ( i ) {
1822  ®case 1, 3, 5®:
1823        ...
1824  ®case 2, 4, 6®:
1825        ...
1826}
1827\end{lstlisting}
1828&
1829\begin{lstlisting}
1830switch ( i ) {
1831  case 1: case 3 : case 5:
1832        ...
1833  case 2: case 4 : case 6:
1834        ...
1835}
1836\end{lstlisting}
1837&
1838\begin{lstlisting}
1839
1840// odd values
1841
1842// even values
1843
1844
1845\end{lstlisting}
1846\end{tabular}
1847\end{quote2}
1848In addition, two forms of subranges are allowed to specify case values: a new \CFA form and an existing GNU C form.\footnote{
1849The GNU C form \emph{requires} spaces around the ellipse.}
1850\begin{quote2}
1851\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1852\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{GNU C}}     \\
1853\begin{lstlisting}
1854switch ( i ) {
1855  ®case 1~5:®
1856        ...
1857  ®case 10~15:®
1858        ...
1859}
1860\end{lstlisting}
1861&
1862\begin{lstlisting}
1863switch ( i )
1864  case 1 ... 5:
1865        ...
1866  case 10 ... 15:
1867        ...
1868}
1869\end{lstlisting}
1870&
1871\begin{lstlisting}
1872
1873// 1, 2, 3, 4, 5
1874
1875// 10, 11, 12, 13, 14, 15
1876
1877
1878\end{lstlisting}
1879\end{tabular}
1880\end{quote2}
1881Lists of subranges are also allowed.
1882\begin{lstlisting}
1883case ®1~5, 12~21, 35~42®:
1884\end{lstlisting}
1885
1886
1887\section{Exception Handling}
1888
1889Exception handling provides two mechanim: change of control flow from a raise to a handler, and commumication from the riase to the handler.
1890\begin{lstlisting}
1891exception void h( int i );
1892exception int h( int i, double d );
1893
1894void f(...) {
1895        ... throw h( 3 );
1896        ... i = resume h( 3, 5.1 );
1897}
1898
1899try {
1900        f(...);
1901} catch h( int w ) {
1902        // reset
1903} resume h( int p, double x ) {
1904        return 17;  // recover
1905} finally {
1906}
1907\end{lstlisting}
1908So the type raised would be the mangled name of the exception prototype and that name would be matched at the handler clauses by comparing the strings.
1909The arguments for the call would have to be packed in a message and unpacked at handler clause and then a call made to the handler.
1910
1911
1912\section{Types}
1913
1914\subsection{Type Definitions}
1915
1916\CFA allows users to define new types using the keyword type.
1917
1918\begin{lstlisting}
1919// SensorValue is a distinct type and represented as an int
1920type SensorValue = int;
1921\end{lstlisting}
1922
1923A type definition is different from a typedef in C because a typedef just creates an alias for a type,  while Do.s type definition creates a distinct type.
1924This means that users can define distinct function overloads for the new type (see Overloading for more information).
1925For example:
1926
1927\begin{lstlisting}
1928type SensorValue = int;
1929void printValue(int v) {...}
1930void printValue(SensorValue v) {...}
1931void process(int v) {...}
1932
1933SensorValue s = ...;
1934
1935printValue(s); // calls version with SensorValue argument
1936
1937printValue((int) s); // calls version with int argument
1938
1939process(s); // implicit conversion to int
1940\end{lstlisting}
1941
1942If SensorValue was defined with a typedef, then these two print functions would not have unique signatures.
1943This can be very useful to create a distinct type that has the same representation as another type.
1944
1945The compiler will assume it can safely convert from the old type to the new type, implicitly.
1946Users may override this and define a function that must be called to convert from one type to another.
1947
1948\begin{lstlisting}
1949type SensorValue = int;
1950// ()? is the overloaded conversion operator identifier
1951// This function converts an int to a SensorValue
1952SensorValue ()?(int val) {
1953        ...
1954}
1955void process(int v) {...}
1956
1957SensorValue s = ...;
1958process(s); // implicit call to conversion operator
1959\end{lstlisting}
1960
1961In many cases, it is not desired for the compiler to do this implicit conversion.
1962To avoid that, the user can use the explicit modifier on the conversion operator.
1963Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error.
1964
1965\begin{lstlisting}
1966type SensorValue = int;
1967
1968// conversion from int to SensorValue; must be explicit
1969explicit SensorValue ()?(int val) {
1970        ...
1971}
1972
1973void process(int v) {...}
1974
1975SensorValue s = ...;
1976process(s); // implicit cast to int: compile-time error
1977process((int) s); // explicit cast to int: calls conversion func
1978\end{lstlisting}
1979
1980The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to:
1981\begin{lstlisting}
1982type SensorValue = int;
1983explicit SensorValue ()?(int);
1984void process(int v) {...}
1985
1986SensorValue s = ...;
1987process(s); // compile-time error
1988process((int) s); // type is converted, no function is called
1989\end{lstlisting}
1990
1991
1992\subsection{Structures}
1993
1994Structures in \CFA are basically the same as structures in C.
1995A structure is defined with the same syntax as in C.
1996When referring to a structure in \CFA, users may omit the struct keyword.
1997\begin{lstlisting}
1998struct Point {
1999        double x;
2000        double y;
2001};
2002
2003Point p = {0.0, 0.0};
2004\end{lstlisting}
2005
2006\CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields.
2007Composition is achieved by embedding one type into another.
2008When type A is embedded in type B, an object with type B may be used as an object of type A, and the fields of type A are directly accessible.
2009Embedding types is achieved using anonymous members.
2010For example, using Point from above:
2011\begin{lstlisting}
2012void foo(Point p);
2013
2014struct ColoredPoint {
2015        Point; // anonymous member (no identifier)
2016        int Color;
2017};
2018...
2019        ColoredPoint cp = ...;
2020        cp.x = 10.3; // x from Point is accessed directly
2021        cp.color = 0x33aaff; // color is accessed normally
2022        foo(cp); // cp can be used directly as a Point
2023\end{lstlisting}
2024
2025
2026\subsection{Constructors and Destructors}
2027
2028\CFA supports C initialization of structures, but it also adds constructors for more advanced initialization.
2029Additionally, \CFA adds destructors that are called when a variable is de-allocated (variable goes out of scope or object is deleted).
2030These functions take a reference to the structure as a parameter (see References for more information).
2031
2032\begin{figure}
2033\begin{lstlisting}
2034struct Widget {
2035        int id;
2036        float size;
2037        Parts *optionalParts;
2038};
2039
2040// ?{} is the constructor operator identifier
2041// The first argument is a reference to the type to initialize
2042// Subsequent arguments can be specified for initialization
2043
2044void ?{}(Widget &w) { // default constructor
2045        w.id = -1;
2046        w.size = 0.0;
2047        w.optionalParts = 0;
2048}
2049
2050// constructor with values (does not need to include all fields)
2051void ?{}(Widget &w, int id, float size) {
2052        w.id = id;
2053        w.size = size;
2054        w.optionalParts = 0;
2055}
2056
2057// ^? is the destructor operator identifier
2058void ^?(Widget &w) { // destructor
2059        w.id = 0;
2060        w.size = 0.0;
2061        if (w.optionalParts != 0) {
2062        // This is the only pointer to optionalParts, free it
2063        free(w.optionalParts);
2064        w.optionalParts = 0;
2065        }
2066}
2067
2068Widget baz; // reserve space only
2069Widget foo{}; // calls default constructor
2070Widget bar{23, 2.45}; // calls constructor with values
2071baz{24, 0.91}; // calls constructor with values
2072?{}(baz, 24, 0.91}; // explicit call to constructor
2073^bar; // explicit call to destructor
2074^?(bar); // explicit call to destructor
2075\end{lstlisting}
2076\caption{Constructors and Destructors}
2077\end{figure}
2078
2079
2080\begin{comment}
2081\section{References}
2082
2083
2084By introducing references in parameter types, users are given an easy way to pass a value by reference, without the need for NULL pointer checks.
2085In structures, a reference can replace a pointer to an object that should always have a valid value.
2086When a structure contains a reference, all of its constructors must initialize the reference and all instances of this structure must initialize it upon definition.
2087
2088The syntax for using references in \CFA is the same as \CC with the exception of reference initialization.
2089Use ©&© to specify a reference, and access references just like regular objects, not like pointers (use dot notation to access fields).
2090When initializing a reference, \CFA uses a different syntax which differentiates reference initialization from assignment to a reference.
2091The ©&© is used on both sides of the expression to clarify that the address of the reference is being set to the address of the variable to which it refers.
2092\end{comment}
2093
2094
2095\section{Overloading}
2096
2097Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name.
2098In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C.
2099This may cause identical C and \CFA programs to behave differently.
2100The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used.
2101Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users.
2102Disadvantages of overloading are that it can be used to give functions with different semantics the same name, causing confusion, or that the compiler may resolve to a different function from what the programmer expected.
2103\CFA allows overloading of functions, operators, variables, and even the constants 0 and 1.
2104
2105The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads.
2106The best valid interpretations are the valid interpretations that use the fewest unsafe conversions.
2107Of these, the best are those where the functions and objects involved are the least polymorphic.
2108Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions.
2109Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions.
2110If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous.
2111For details about type inference and overload resolution, please see the \CFA Language Specification.
2112\begin{lstlisting}
2113int foo(int a, int b) {
2114        float sum = 0.0;
2115        float special = 1.0;
2116        {
2117                int sum = 0;
2118                // both the float and int versions of sum are available
2119                float special = 4.0;
2120                // this inner special hides the outer version
2121                ...
2122        }
2123        ...
2124}
2125\end{lstlisting}
2126
2127
2128\subsection{Overloaded Constant}
2129
2130The constants 0 and 1 have special meaning.
2131In \CFA, as in C, all scalar types can be incremented and
2132decremented, which is defined in terms of adding or subtracting 1.
2133The operations ©&&©, ©||©, and ©!© can be applied to any scalar arguments and are defined in terms of comparison against 0 (ex. ©(a && b)© becomes ©(a != 0 && b != 0)©).
2134
2135In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a special case.
2136However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their polymorphic parameters, and user-defined pointer-like types may need a null value.
2137Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©.
2138
2139Why just 0 and 1? Why not other integers? No other integers have special status in C.
2140A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement.
2141Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed.
2142The complexity of such a feature doesn.t seem worth the gain.
2143
2144For example, to define the constants for a complex type, the programmer would define the following:
2145
2146\begin{lstlisting}
2147struct Complex {
2148        double real;
2149        double imaginary;
2150}
2151
2152const Complex 0 = {0, 0};
2153const Complex 1 = {1, 0};
2154...
2155
2156        Complex a = 0;
2157...
2158
2159        a++;
2160...
2161        if (a) { // same as if (a == 0)
2162...
2163}
2164\end{lstlisting}
2165
2166
2167\subsection{Variable Overloading}
2168
2169The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types.
2170Allowing overloading of variable names enables programmers to use the same name across multiple types, simplifying naming conventions and is compatible with the other overloading that is allowed.
2171For example, a developer may want to do the following:
2172\begin{lstlisting}
2173int pi = 3;
2174float pi = 3.14;
2175char pi = .p.;
2176\end{lstlisting}
2177
2178
2179\subsection{Function Overloading}
2180
2181Overloaded functions in \CFA are resolved based on the number and type of arguments, type of return value, and the level of specialization required (specialized functions are preferred over generic).
2182
2183The examples below give some basic intuition about how the resolution works.
2184\begin{lstlisting}
2185// Choose the one with less conversions
2186int doSomething(int value) {...} // option 1
2187int doSomething(short value) {...} // option 2
2188
2189int a, b = 4;
2190short c = 2;
2191
2192a = doSomething(b); // chooses option 1
2193a = doSomething(c); // chooses option 2
2194
2195// Choose the specialized version over the generic
2196
2197generic(type T)
2198T bar(T rhs, T lhs) {...} // option 3
2199float bar(float rhs, float lhs){...} // option 4
2200float a, b, c;
2201double d, e, f;
2202c = bar(a, b); // chooses option 4
2203
2204// specialization is preferred over unsafe conversions
2205
2206f = bar(d, e); // chooses option 5
2207\end{lstlisting}
2208
2209
2210\subsection{Operator Overloading}
2211
2212\CFA also allows operators to be overloaded, to simplify the use of user-defined types.
2213Overloading the operators allows the users to use the same syntax for their custom types that they use for built-in types, increasing readability and improving productivity.
2214\CFA uses the following special identifiers to name overloaded operators:
2215
2216\begin{table}[hbt]
2217\hfil
2218\begin{tabular}[t]{ll}
2219%identifier & operation \\ \hline
2220©?[?]© & subscripting \impl{?[?]}\\
2221©?()© & function call \impl{?()}\\
2222©?++© & postfix increment \impl{?++}\\
2223©?--© & postfix decrement \impl{?--}\\
2224©++?© & prefix increment \impl{++?}\\
2225©--?© & prefix decrement \impl{--?}\\
2226©*?© & dereference \impl{*?}\\
2227©+?© & unary plus \impl{+?}\\
2228©-?© & arithmetic negation \impl{-?}\\
2229©~?© & bitwise negation \impl{~?}\\
2230©!?© & logical complement \impl{"!?}\\
2231©?*?© & multiplication \impl{?*?}\\
2232©?/?© & division \impl{?/?}\\
2233\end{tabular}\hfil
2234\begin{tabular}[t]{ll}
2235%identifier & operation \\ \hline
2236©?%?© & remainder \impl{?%?}\\
2237©?+?© & addition \impl{?+?}\\
2238©?-?© & subtraction \impl{?-?}\\
2239©?<<?© & left shift \impl{?<<?}\\
2240©?>>?© & right shift \impl{?>>?}\\
2241©?<?© & less than \impl{?<?}\\
2242©?<=?© & less than or equal \impl{?<=?}\\
2243©?>=?© & greater than or equal \impl{?>=?}\\
2244©?>?© & greater than \impl{?>?}\\
2245©?==?© & equality \impl{?==?}\\
2246©?!=?© & inequality \impl{?"!=?}\\
2247©?&& bitwise AND \impl{?&?}\\
2248\end{tabular}\hfil
2249\begin{tabular}[t]{ll}
2250%identifier & operation \\ \hline
2251©?^& exclusive OR \impl{?^?}\\
2252©?|?© & inclusive OR \impl{?"|?}\\
2253©?=?© & simple assignment \impl{?=?}\\
2254©?*=?© & multiplication assignment \impl{?*=?}\\
2255©?/=?© & division assignment \impl{?/=?}\\
2256©?%=?© & remainder assignment \impl{?%=?}\\
2257©?+=?© & addition assignment \impl{?+=?}\\
2258©?-=?© & subtraction assignment \impl{?-=?}\\
2259©?<<=?© & left-shift assignment \impl{?<<=?}\\
2260©?>>=?© & right-shift assignment \impl{?>>=?}\\
2261©?&=?© & bitwise AND assignment \impl{?&=?}\\
2262©?^=?© & exclusive OR assignment \impl{?^=?}\\
2263©?|=?© & inclusive OR assignment \impl{?"|=?}\\
2264\end{tabular}
2265\hfil
2266\caption{Operator Identifiers}
2267\label{opids}
2268\end{table}
2269
2270These identifiers are defined such that the question marks in the name identify the location of the operands.
2271These operands represent the parameters to the functions, and define how the operands are mapped to the function call.
2272For example, ©a + b© becomes ©?+?(a, b)©.
2273
2274In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator.
2275These operators are called using the normal C syntax.
2276
2277\begin{lstlisting}
2278type Complex = struct { // define a Complex type
2279        double real;
2280        double imag;
2281}
2282
2283// Constructor with default values
2284
2285void ?{}(Complex &c, double real = 0.0, double imag = 0.0) {
2286        c.real = real;
2287        c.imag = imag;
2288}
2289
2290Complex ?+?(Complex lhs, Complex rhs) {
2291        Complex sum;
2292        sum.real = lhs.real + rhs.real;
2293        sum.imag = lhs.imag + rhs.imag;
2294        return sum;
2295}
2296
2297String ()?(const Complex c) {
2298        // use the string conversions for the structure members
2299        return (String)c.real + . + . + (String)c.imag + .i.;
2300}
2301...
2302
2303Complex a, b, c = {1.0}; // constructor for c w/ default imag
2304...
2305c = a + b;
2306print(.sum = . + c);
2307\end{lstlisting}
2308
2309
2310\section{Auto Type-Inferencing}
2311
2312Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type.
2313\begin{quote2}
2314\begin{tabular}{@{}l@{\hspace{3em}}ll@{}}
2315\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{Indexc{gcc}} \\
2316\begin{lstlisting}
2317
2318auto j = 3.0 * 4;
2319int i;
2320auto k = i;
2321\end{lstlisting}
2322&
2323\begin{lstlisting}
2324#define expr 3.0 * i
2325typeof(expr) j = expr;
2326int i;
2327typeof(i) k = i;
2328\end{lstlisting}
2329&
2330\begin{lstlisting}
2331
2332// use type of initialization expression
2333
2334// use type of primary variable
2335\end{lstlisting}
2336\end{tabular}
2337\end{quote2}
2338The two important capabilities are:
2339\begin{itemize}
2340\item
2341preventing having to determine or write out long generic types,
2342\item
2343ensure secondary variables, related to a primary variable, always have the same type.
2344\end{itemize}
2345
2346In \CFA, ©typedef© provides a mechanism to alias long type names with short ones, both globally and locally, but not eliminate the use of the short name.
2347\Indexc{gcc} provides ©typeof© to declare a secondary variable from a primary variable.
2348\CFA also relies heavily on the specification of the left-hand side of assignment for type inferencing, so in many cases it is crucial to specify the type of the left-hand side to select the correct type of the right-hand expression.
2349Only for overloaded routines with the same return type is variable type-inferencing possible.
2350Finally, ©auto© presents the programming problem of tracking down a type when the type is actually needed.
2351For example, given
2352\begin{lstlisting}
2353auto j = ®...®
2354\end{lstlisting}
2355and the need to write a routine to compute using ©j©
2356\begin{lstlisting}
2357void rtn( ®...® parm );
2358rtn( j );
2359\end{lstlisting}
2360A programmer must work backwards to determine the type of ©j©'s initialization expression, reconstructing the possibly long generic type-name.
2361In this situation, having the type name or a short alias is very useful.
2362
2363There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type.
2364That is, when is the type of the variable more important than the type of its initialization expression.
2365For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors.
2366At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes.
2367
2368Given ©typedef© and ©typeof© in \CFA, and the strong need to use the type of left-hand side in inferencing, auto type-inferencing is not supported at this time.
2369Should a significant need arise, this feature can be revisited.
2370
2371
2372\section{Generics}
2373
2374\CFA supports parametric polymorphism to allow users to define generic functions and types.
2375Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types.
2376The type parameters can be restricted to satisfy a set of constraints.
2377This enables \CFA to build fully compiled generic functions and types, unlike other languages like \Index*[C++]{\CC} where templates are expanded or must be explicitly instantiated.
2378
2379
2380\subsection{Generic Functions}
2381
2382Generic functions in \CFA are similar to template functions in \Index*[C++]{\CC}, and will sometimes be expanded into specialized versions, just like in \CC.
2383The difference, however, is that generic functions in \CFA can also be separately compiled, using function pointers for callers to pass in all needed functionality for the given type.
2384This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically).
2385Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated.
2386
2387A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this:
2388
2389\begin{lstlisting}
2390generic(type T)
2391void swap(T &a, T &b) {
2392        T tmp = a;
2393        a = b;
2394        b = a;
2395}
2396
2397int a, b;
2398swap(a, b);
2399
2400Point p1, p2;
2401swap(p1, p2);
2402\end{lstlisting}
2403
2404Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T.
2405This function can be called with any type, and the compiler will handle generating the proper code for that type, using call site inference to determine the appropriate value for T.
2406
2407
2408\subsection{Bounded Quantification}
2409
2410Some generic functions only work (or make sense) for any type that satisfies a given property.
2411For example, here is a function to pick the minimum of two values of some type.
2412\begin{lstlisting}
2413generic (type T | bool ?<?(T, T) )
2414
2415T min(T a, T b) {
2416        return a < b ? a : b;
2417}
2418\end{lstlisting}
2419
2420It only makes sense to call min with values of a type that has an ordering: a way to decide whether one value is less than another.
2421The ordering function used here is the less than operator, <.
2422The syntax used to reference the operator is discussed in further detail in Operator Overloading.
2423In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)).
2424The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise.
2425
2426Bounds can also involve multiple types, and multiple requirements, as shown below:
2427\begin{lstlisting}
2428generic (type T, type U | { T foo(T, U); U bar(U); })
2429
2430T baz(T t, U u) {
2431        return foo(t, bar(u));
2432}
2433\end{lstlisting}
2434
2435
2436\subsection{Interfaces}
2437
2438Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type.
2439Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined.
2440Can you define it? What is it supposed to do? Perhaps it should compute the sum, or the bitwise and, or the maximum, or the least common multiple; or perhaps it's an operation that can't be defined for integers.
2441The function signature doesn't say.
2442
2443Interfaces gather together a set of function signatures under a common name, which solves two problems.
2444First, an interface name can be used in type bounds instead of function signatures.
2445This avoids repetition when a bound is used in many functions.
2446Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand.
2447\begin{lstlisting}
2448generic (type T)
2449interface Orderable {
2450        bool ?<?(T, T);
2451};
2452
2453generic (type T | Orderable(T))
2454T min(T a, T b) {
2455        return a < b ? a : b;
2456}
2457\end{lstlisting}
2458
2459This definition of the interface Orderable makes the generic function min easier to read and understand.
2460Orderable can also be reused for other generic functions, max for example.
2461Interfaces can also build on top of other interfaces.
2462For example:
2463\begin{lstlisting}
2464generic (type T | Orderable(T)
2465interface FooBarable {
2466        int foo(T, T);
2467        int Bar(T, T);
2468};
2469\end{lstlisting}
2470
2471The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition.
2472A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time.
2473For example, there is no need to add some special syntax to show that a type implements the Orderable interface, just define a ?<? operator and it is satisfied.
2474
2475
2476\subsection{Generic Typedefs}
2477
2478Type synonyms can be defined generically using the typedef keyword together with a generic type annotation.
2479These can be used to abbreviate complicated type expressions, especially in generic code.
2480\begin{lstlisting}
2481// typedef the generic function pointers for later use
2482
2483generic(type T)
2484typedef int (*predicate)(T);
2485generic(type Captured, type T)
2486typedef void (*callback)(Captured, T);
2487
2488generic(type T)
2489void find(int length, T *array,
2490        predicate(T) p, callback(void *, T)f) {
2491        int i;
2492        for (i = 0; i < length; i++)
2493        if (p(array[i])) f(NULL, array[i]);
2494}
2495\end{lstlisting}
2496
2497
2498\subsection{Generic Types}
2499
2500Generic types are defined using the same mechanisms as those described above for generic functions.
2501This feature allows users to create types that have one or more fields that use generic parameters as types, similar to a template classes in \Index*[C++]{\CC}.
2502For example, to make a generic linked list, a placeholder is created for the type of the elements, so that the specific type of the elements in the list need not be specified when defining the list.
2503In C, something like this would have to be done using void pointers and unsafe casting.
2504As in generic functions, Do.s generic types are different from \CC templates in that they can be fully compiled, while \CC templates are more like macro expansions.
2505This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds.
2506
2507The syntax for defining a generic type looks very similar to that of a generic function.
2508Generic types support bounds and interfaces, using the same syntax as generic functions.
2509\begin{lstlisting}
2510generic (type T)
2511struct LinkedListElem {
2512        T elem;
2513        LinkedListElem(T) *next;
2514};
2515
2516LinkedListElem *++?(LinkedListElem **elem) {
2517        return *elem = elem->next;
2518}
2519
2520generic (type T)
2521struct LinkedList {
2522        LinkedListElem(T) *head;
2523        unsigned int size;
2524}
2525
2526generic (type T | bool ?==?(T, T))
2527bool contains(LinkedList(T) *list, T elem) {
2528        for(LinkedListElem *iter = list->head; iter != 0; ++iter) {
2529        if (iter->elem == elem) return true;
2530        }
2531        return false;
2532}
2533\end{lstlisting}
2534
2535
2536\section{Safety}
2537
2538Safety, along with productivity, is a key goal of Do.
2539This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code.
2540
2541
2542\subsection{Exceptions}
2543
2544\CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code.
2545In C, developers can use error codes and special return values to report to a caller that an error occurred in a function.
2546The major problem with error codes is that they can be easily ignored by the caller.
2547Failure to properly check for errors can result in the caller making incorrect assumptions about the current state or about the return value that are very likely to result in errors later on in the program, making the source of the problem more difficult to find when debugging.
2548An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state.
2549
2550Exceptions in \CFA allow a different type of control flow.
2551Throwing an exception terminates execution of the current block, invokes the destructors of variables that are local to the block, and propagates the exception to the parent block.
2552The exception is immediately re-thrown from the parent block unless it is caught as described below.
2553\CFA uses keywords similar to \Index*[C++]{\CC} for exception handling.
2554An exception is thrown using a throw statement, which accepts one argument.
2555
2556\begin{lstlisting}
2557        ...
2558
2559        throw 13;
2560
2561        ...
2562\end{lstlisting}
2563
2564An exception can be caught using a catch statement, which specifies the type of the exception it can catch.
2565A catch is specified immediately after a guarded block to signify that it can catch an exception from that block.
2566A guarded block is specified using the try keyword, followed by a block of code inside of curly braces.
2567
2568\begin{lstlisting}
2569        ...
2570
2571        try {
2572                throw 13;
2573        }
2574        catch(int e) {
2575                printf(.caught an exception: %d\n., e);
2576        }
2577\end{lstlisting}
2578
2579
2580\subsection{Memory Management}
2581
2582
2583\subsubsection{Manual Memory Management}
2584
2585Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
2586First, malloc breaks type safety because it returns a pointer to void.
2587There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
2588This problem is solved with a type-safe malloc.
2589Do.s type-safe malloc does not take any arguments for size.
2590Instead, it infers the type based on the return value, and then allocates space for the inferred type.
2591
2592\begin{lstlisting}
2593float *f = malloc(); // allocates the size of a float
2594
2595struct S {
2596        int i, j, k;
2597};
2598
2599struct S *s = malloc(); // allocates the size of a struct S
2600\end{lstlisting}
2601
2602In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
2603For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
2604
2605\begin{lstlisting}
2606type Complex = struct {
2607        float real;
2608        float imag;
2609};
2610
2611// default constructor
2612
2613void ?{}(Complex &c) {
2614        c.real = 0.0;
2615        c.imag = 0.0;
2616}
2617
2618
2619
2620// 2 parameter constructor
2621
2622void ?{}(Complex &c, float real, float imag) {
2623        c.real = real;
2624        c.imag = imag;
2625}
2626
2627
2628int main() {
2629        Complex c1; // No constructor is called
2630        Complex c2{}; // Default constructor called
2631        Complex c3{1.0, -1.0}; // 2 parameter constructor is called
2632
2633        Complex *p1 = malloc(); // allocate
2634        Complex *p2 = new(); // allocate + default constructor
2635        Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
2636}
2637
2638\end{lstlisting}
2639
2640
2641\subsubsection{Automatic Memory Management}
2642
2643\CFA may also support automatic memory management to further improve safety.
2644If the compiler can insert all of the code needed to manage dynamically allocated memory (automatic reference counting), then developers can avoid problems with dangling pointers, double frees, memory leaks, etc.
2645This feature requires further investigation.
2646\CFA will not have a garbage collector, but might use some kind of region-based memory management.
2647
2648
2649\subsection{Unsafe C Constructs}
2650
2651C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
2652Some of these practices however are often error-prone and difficult to read and maintain.
2653Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
2654If a programmer wants to use one of these unsafe C constructs, the unsafe code must be contained in a C linkage block (see Interoperability), which will be compiled like C code.
2655This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
2656
2657The exact set of unsafe C constructs that will be disallowed in \CFA has not yet been decided, but is sure to include pointer arithmetic, pointer casting, etc.
2658Once the full set is decided, the rules will be listed here.
2659
2660
2661\section{Syntactic Anomalies}
2662
2663The number 0 and 1 are treated specially in \CFA, and can be redefined as variables.
2664One syntactic anomaly is when a field in an structure is names 0 or 1:
2665\begin{lstlisting}
2666struct S {
2667        int 0, 1;
2668} s;
2669\end{lstlisting}
2670The problem occurs in accesing these fields using the selection operation ``©.©'':
2671\begin{lstlisting}
2672s.0 = 0;        // ambiguity with floating constant .0
2673s.1 = 1;        // ambiguity with floating constant .1
2674\end{lstlisting}
2675To make this work, a space is required after the field selection:
2676\begin{lstlisting}
2677®s.§\textvisiblespace§0® = 0;
2678®s.§\textvisiblespace§1® = 1;
2679\end{lstlisting}
2680While this sytact is awkward, it is unlikely many programers will name fields of a structure 0 or 1.
2681Like the \Index*[C++]{\CC} lexical problem with closing template-syntax, e.g, ©Foo<Bar<int®>>®©, this issue can be solved with a more powerful lexer/parser.
2682
2683There are several ambiguous cases with operator identifiers, e.g., ©int *?*?()©, where the string ©*?*?© can be lexed as ©*©/©?*?© or ©*?©/©*?©.
2684Since it is common practise to put a unary operator juxtaposed to an identifier, e.g., ©*i©, users will be annoyed if they cannot do this with respect to operator identifiers.
2685Even with this special hack, there are 5 general cases that cannot be handled.
2686The first case is for the function-call identifier ©?()©:
2687\begin{lstlisting}
2688int *§\textvisiblespace§?()();  // declaration: space required after '*'
2689\textvisiblespace§?()();              // expression: space required after '*'
2690\end{lstlisting}
2691Without the space, the string ©*?()© is ambiguous without N character look ahead;
2692it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument/parameter list.
2693
2694The 4 remaining cases occur in expressions:
2695\begin{lstlisting}
2696i++§\textvisiblespace§?i:0;             // space required before '?'
2697i--§\textvisiblespace§?i:0;             // space required before '?'
2698\textvisiblespace§?++i:0;             // space required after '?'
2699\textvisiblespace§?--i:0;             // space required after '?'
2700\end{lstlisting}
2701In the first two cases, the string ©i++?© is ambiguous, where this string can be lexed as ©i© / ©++?© or ©i++© / ©?©;
2702it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument list.
2703In the second two cases, the string ©?++x© is ambiguous, where this string can be lexed as ©?++© / ©x© or ©?© / y©++x©;
2704it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument list.
2705
2706
2707\section{Concurrency}
2708
2709Today's processors for nearly all use cases, ranging from embedded systems to large cloud computing servers, are composed of multiple cores, often heterogeneous.
2710As machines grow in complexity, it becomes more difficult for a program to make the most use of the hardware available.
2711\CFA includes built-in concurrency features to enable high performance and improve programmer productivity on these multi-/many-core machines.
2712
2713Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads.
2714The model integrates concurrency features into the language by making the structure type the core unit of concurrency.
2715All communication occurs through method calls, where data is sent via method arguments, and received via the return value.
2716This enables a very familiar interface to all programmers, even those with no parallel programming experience.
2717It also allows the compiler to do static type checking of all communication, a very important safety feature.
2718This controlled communication with type safety has some similarities with channels in \Index*{Go}, and can actually implement
2719channels exactly, as well as create additional communication patterns that channels cannot.
2720Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads.
2721
2722Three new keywords are added to support these features:
2723
2724monitor creates a structure with implicit locking when accessing fields
2725
2726mutex implies use of a monitor requiring the implicit locking
2727
2728task creates a type with implicit locking, separate stack, and a thread
2729
2730
2731\subsection{Monitors}
2732
2733A monitor is a structure in \CFA which includes implicit locking of its fields.
2734Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion.
2735An example of the definition of a monitor is shown here:
2736\begin{lstlisting}
2737type Account = monitor {
2738        const unsigned long number; // account number
2739        float balance; // account balance
2740};
2741\end{lstlisting}
2742
2743Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor;
2744it is always passed by reference.
2745Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter.
2746When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body.
2747This means that a function requiring mutual exclusion could block if the lock is already held by another thread.
2748Blocking on a monitor lock does not block the kernel thread, it simply blocks the user thread, which yields its kernel thread while waiting to obtain the lock.
2749If multiple mutex parameters are specified, they will be locked in parameter order (i.e. first parameter is locked first) and unlocked in the
2750reverse order.
2751\begin{lstlisting}
2752// This function accesses a constant field, it does not require
2753// mutual exclusion
2754
2755export unsigned long getAccountNumber(Account &a) {
2756        return a.number;
2757}
2758
2759// This function accesses and modifies a shared field; it
2760// requires mutual exclusion
2761
2762export float withdrawal(mutex Account &a, float amount) {
2763        a.balance -= amount;
2764        return a.balance;
2765}
2766\end{lstlisting}
2767
2768Often, one function using a monitor will call another function using that same monitor.
2769If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function.
2770This situation is resolved by allowing recursive entry (reentrant locks), meaning that if the lock is already held by the caller, it can be locked again.
2771It will still be unlocked the same number of times.
2772An example of this situation is shown below:
2773
2774\begin{lstlisting}
2775// deleting a job from a worker requires mutual exclusion
2776
2777void deleteJob(mutex Worker &w, Job &j) {
2778        ...
2779}
2780
2781// transferring requires mutual exclusion and calls deleteJob
2782
2783void transferJob(mutex Worker &from, Worker &to) {
2784        ...
2785        deleteJob(j);
2786        ...
2787}
2788\end{lstlisting}
2789
2790
2791\subsection{Tasks}
2792
2793\CFA also provides a simple mechanism for creating and utilizing user level threads.
2794A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control.
2795Similar to a monitor, a task is defined like a structure:
2796\begin{lstlisting}
2797type Adder = task {
2798        int *row;
2799        int size;
2800        int &subtotal;
2801}
2802\end{lstlisting}
2803
2804A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
2805A destructor may also be defined, which is called at de-allocation (when a dynamic object is deleted or when a local object goes out of scope).
2806After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
2807All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
2808Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
2809(Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
2810\begin{lstlisting}
2811void ?{}(Adder &a, int r[], int s, int &st) { // constructor
2812        a.row = r;
2813        a.size = s;
2814        a.subtotal = st;
2815}
2816
2817// implicitly spawn thread and begin execution here
2818
2819void ?()(Adder &a) {
2820        int c;
2821        subtotal = 0;
2822        for (c=0; c<a.size; ++c) {
2823        subtotal += row[c];
2824        }
2825}
2826
2827int main() {
2828        const int rows = 100, cols = 1000000;
2829        int matrix[rows][cols];
2830        int subtotals[rows];
2831        int total = 0;
2832        int r;
2833
2834        { // create a new scope here for our adders
2835        Adder adders[rows];
2836        // read in the matrix
2837        ...
2838        for (r=0; r<rows; ++r) {
2839        // tasks are initialized on this thread
2840        Adders[r] = {matrix[r], cols, subtotals[r]};
2841        Adders[r](); // spawn thread and begin execution
2842        }
2843        } // adders go out of scope; block here until they all finish
2844        total += subtotals[r];
2845        printf(.total is %d\n., total);
2846}
2847\end{lstlisting}
2848
2849
2850\subsection{Cooperative Scheduling}
2851
2852Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
2853In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
2854Places where a task could yield include waiting for a lock (explicitly or implicitly), waiting for I/O, or waiting for a specific function (or one of a set of functions) to be called.
2855This last option is introduced with the yield function. yield is used to indicate that this task should yield its thread until the specified function is called.
2856For example, the code below defines a monitor that maintains a generic list.
2857When a task tries to pop from the list, but it is empty, the task should yield until another task puts something into the list, with the push function.
2858Similarly, when a task tries to push something onto the list, but it is full, it will yield until another task frees some space with the pop function.
2859
2860\begin{lstlisting}
2861// type T is used as a generic type for all definitions inside
2862// the curly brackets
2863
2864generic(type T) {
2865        type Channel = monitor {
2866        List(T) list; // list is a simple generic list type
2867        };
2868
2869        T pop(mutex &Channel(T) ch) {
2870        if (ch.list.empty()) {
2871        // yield until push is called for this channel
2872        yield(push);
2873        }
2874        return ch.list.pop();
2875        }
2876
2877        void push(mutex &Channel(T)ch, T val) {
2878        if (ch.list.full()) {
2879        // yield until pop is called for this channel
2880        yield(pop);
2881        }
2882        ch.list.push(val);
2883        }
2884}
2885\end{lstlisting}
2886
2887A task can also yield indefinitely by calling yield with no arguments.
2888This will tell the scheduler to yield this task until it is resumed by some other task.
2889A task can resume another task by using its functional call operator.
2890The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
2891
2892\begin{lstlisting}
2893type Ping = task {
2894        Pong *partner;
2895};
2896
2897void ?{}(Ping &p, Pong *partner = 0) {
2898        p.partner = partner;
2899}
2900
2901void ?()(Ping &p) {
2902        for(;;) { // loop forever
2903        printf(.ping\n.);
2904        partner(); // resumes the partner task
2905        yield(); // yields this task
2906        }
2907}
2908
2909type Pong = task {
2910        Ping *partner;
2911};
2912
2913void ?{}(Pong &p, Ping *partner = 0) {
2914        p.partner = partner;
2915}
2916
2917void ?()(Pong &p) {
2918        for(;;) { // loop forever
2919        yield(); // yields this task
2920        printf(.pong/n.);
2921        partner(); // resumes the partner task
2922        }
2923}
2924
2925void main() {
2926        Ping ping; // allocate ping
2927        Pong pong{ping}; // allocate, initialize, and start pong
2928        Ping{pong}; // initialize and start ping
2929}
2930\end{lstlisting}
2931
2932The same functionality can be accomplished by providing functions to be called by the partner task.
2933\begin{lstlisting}
2934type Pingpong = task {
2935        String msg;
2936        Pingpong *partner;
2937};
2938
2939void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
2940        p.msg = msg;
2941        p.partner = partner;
2942}
2943
2944void ?()(Pingpong &p) {
2945        for(;;) {
2946        yield(go);
2947        }
2948}
2949
2950void go(Pingpong &p) {
2951        print(.%(p.msg)\n.);
2952        go(p.partner);
2953}
2954
2955void main() {
2956        Pingpong ping = {.ping.};
2957        Pingpong pong = {.pong., ping};
2958        ping.partner = pong;
2959        go(ping);
2960}
2961\end{lstlisting}
2962
2963
2964\section{Modules and Packages }
2965
2966\begin{comment}
2967High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed.
2968\CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time.
2969
2970There are two levels of encapsulation in \CFA, module and package.
2971A module is a logical grouping of functionality that can be easily pulled into another project, much like a module in \Index*{Python} or a package in \Index*{Go}.
2972A module forms a namespace to limit the visibility and prevent naming conflicts of variables.
2973Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed.
2974
2975A package is a physical grouping of one or more modules that is used for code distribution and version management.
2976Package is also the level of granularity at which dependences are managed.
2977A package is similar to the Crate in \Index*{Rust}.
2978
2979
2980\subsection{No Declarations, No Header Files}
2981
2982In C and \Index*[C++]{\CC}, it is necessary to declare or define every global variable, global function, and type before it is used in each file.
2983Header files and a preprocessor are normally used to avoid repeating code.
2984Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work.
2985Instead of following this model, the \CFA tools can extract all of the same information from the code automatically.
2986This information is then stored in the object files for each module, in a format that can quickly be read by the compiler, and stored at the top of the file, for quick access.
2987In addition to the user productivity improvements, this simple change also improves compile time, by saving the information in a simple machine readable format, instead of making the compiler parse the same information over and over from a header file.
2988This seems like a minor change, but according to (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering), this simple change can cause massive reductions in compile time.
2989
2990In \CFA, multiple definitions are not necessary.
2991Within a module, all of the module's global definitions are visible throughout the module.
2992For example, the following code compiles, even though isOdd was not declared before being called:
2993\begin{lstlisting}
2994bool isEven(unsigned int x) {
2995        if (x == 0) return true;
2996        else return !isOdd(x);
2997}
2998
2999bool isOdd(unsigned int x) {
3000        if (x == 1) return true;
3001        else return !isEven(x - 2);
3002}
3003\end{lstlisting}
3004
3005Header files in C are used to expose the declarations from a library, so that they can be used externally.
3006With \CFA, this functionality is replaced with module exports, discussed below.
3007When building a \CFA module which needs to be callable from C code, users can use the tools to generate a header file suitable for including in these C files with all of the needed declarations.
3008
3009In order to interoperate with existing C code, \CFA files can still include header files, the contents of which will be enclosed in a C linkage section to indicate C calling conventions (see Interoperability for more information).
3010
3011
3012\subsection{Modules}
3013
3014A module typically contains a set of related types and methods, with some objects accessible from outside the package, and some limited to use inside the module.
3015These modules can then be easily shared and reused in multiple projects.
3016As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces.
3017
3018\CFA adds the following keywords to express the module systems: module, export, import, as.
3019
3020
3021\subsubsection{Module Declaration}
3022
3023The syntax to declare a module is module moduleName;.
3024
3025The module declaration must be at the beginning of a file, and each file can only belong to one module.
3026If there is no module declaration at the beginning of a file, the file belongs to the global module.
3027A module can span several files.
3028By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation.
3029
3030The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship.
3031For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container.
3032
3033Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface.
3034A method, a global variable or a type can be declared as a module interface.
3035Types defined in a module and referenced by an exported function or a variable must be exported, too.
3036
3037The following code is a simple module declaration example.
3038\begin{lstlisting}
3039module M;
3040
3041//visible outside module M
3042
3043export int f(int i) { return i + 1; }
3044export double aCounter;
3045
3046//not visible outside module M
3047
3048int g(int i) { return i - 1; }
3049
3050double bCounter;
3051\end{lstlisting}
3052
3053export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module.
3054
3055
3056\subsubsection{Module Import}
3057
3058The syntax to import a module is import moduleName; or import moduleName as anotherName;.
3059One package cannot be imported with both of the two types of syntax in one file.
3060A package imported in one file will only be visible in this file.
3061For example, two files, A and B belong to the same module.
3062If file A imports another module, M, the exported names in M are not visible in file B.
3063
3064All of the exported names are visible in the file that imports the module.
3065The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo).
3066If moduleName has several elements separated by '/' to describe a sub-module (ex. import container/vector;), the last element in the moduleName is used as the namespace to access the visible names in that module (ex vector.add(...);).
3067The as keyword is used to confine the imported names in a unique namespace (ex. anotherName.foo). anotherName must be a valid identifier (same rules as a variable name) which means it cannot have '/' in it.
3068Conflicts in namespaces will be reported by the compiler.
3069The second method can be used to solve conflicting name problems.
3070The following code snippets show the two situations.
3071
3072\begin{lstlisting}
3073module util/counter;
3074export int f(int i) { return i+1; }
3075
3076import util/counter;
3077
3078int main() {
3079        return counter.f(200); // f() from the package counter
3080}
3081
3082import util/counter as ct;
3083int main() {
3084        return ct.f(200); // f() from the package counter
3085}
3086\end{lstlisting}
3087
3088
3089Additionally, using the .as. syntax, a user can force the compiler to add the imported names into the current namespace using .as ..With these module rules, the following module definitions and imports can be achieved without any problem.
3090
3091\begin{lstlisting}
3092module M1;
3093export int f(int i) { return i+1;} // visible outside
3094
3095int g(int i) { return i-1;} // not visible outside
3096
3097module M2;
3098int f(int i) { return i * 2; } // not visible outside
3099export int g(int g) { return i / 2; } // visible outside
3100
3101import M1 as .;
3102
3103import M2 as .;
3104
3105
3106int main() {
3107        return f(3) + g(4); //f() from M1 and g() from M2;
3108}
3109\end{lstlisting}
3110
3111
3112\subsubsection{Sub-Module and Module Aggregation}
3113
3114Several modules can be organized in a parent module and sub-modules relationship.
3115The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship.
3116For example, std/vector and std/io are sub-modules of module std.
3117The exported names in a sub-module are NOT visible if the parent module is imported, which means the exported names in the sub-module are
3118not implicitly exported in the parent module.
3119
3120Aggregation is a mechanism to support components and simplified importing.
3121The mechanism is not based on naming but based on manual declaration.
3122For example, the following is the aggregated sequence module.
3123The export {...} is syntactic sugar for many lines of export module aModule;.
3124If an aggregated module is imported, all the included modules in the aggregation are imported.
3125
3126\begin{lstlisting}
3127module std/sequence;
3128
3129export {
3130        module std/vector;
3131        module std/list;
3132        module std/array;
3133        module std/deque;
3134        module std/forward_list;
3135        module std/queue;
3136        module std/stack;
3137};
3138\end{lstlisting}
3139
3140After importing the aggregated module, each individual name is still contained in the original name space.
3141For example, vector.add() and list.add() should be used to reference the add methods if there are add methods in both the vector module and the list module.
3142
3143
3144\subsubsection{Import from Repository}
3145
3146When a module is imported, the tools locate the module in the one of the accessible package paths (defined by command line flag or environment variable).
3147The tools also support retrieving modules of a package from external repositories.
3148See Listing 40: Package directory structure
3149
3150
3151\subsubsection{Package Import}
3152
3153Because packages are the places where the building tool looks for modules, there is no code required in the \CFA source file to import a package.
3154In order to use modules in a package, the programmer needs to guide the building tool to locate the right package by 1) Adding the package's parent path into \$DOPATH;
3155or 2) Adding the package dependence into the current project's Do.prj.
3156More details about locating a module in a package are explained in the next section.
3157
3158
3159\subsubsection{Package Versioning}
3160
3161A package must have a version number.
3162The version number is a string.
3163For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3164By convention, a package is stored in a directory named packageName-packageVersion.
3165For example, the util package with version 1.1 is stored in a directory named util-1.1.
3166
3167The project description file can optionally specify the version of the package used in the current project.
3168If not defined, because the version number is a string, and all the different versions for the same package will be sorted in increasing order, the package with the largest version number will be used in the compilation.
3169The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3170
3171
3172\subsection{Module and Package Organization}
3173
3174\CFA has two level of encapsulations, module and package.
3175This section explains the object model of modules, packages and other language concepts.
3176It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3177
3178
3179\subsubsection{Object Model}
3180
3181There are several concepts in Do.
3182\begin{itemize}
3183\item
3184File: a \CFA source file
3185\item
3186Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3187\item
3188Package: a container to organize modules for distribution; It has attributes like name, author,
3189version, dependences, etc.
3190\item
3191Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3192\end{itemize}
3193
3194The following rules summarize the object model of all the above concepts:
3195\begin{itemize}
3196\item
3197A module contains one or more files
3198\begin{itemize}
3199\item
3200One file can only belong to one module
3201\item
3202A module has its name and interfaces exported
3203\item
3204A file without a module declaration at the beginning belongs to the global module
3205\item
3206\end{itemize}
3207
3208\item
3209A package contains one or more modules
3210\begin{itemize}
3211\item
3212A package has additional meta info described in Do.prj file
3213\item
3214A package may be dependent on other packages.
3215\end{itemize}
3216
3217\item
3218A project contains one or more modules in its source code
3219\begin{itemize}
3220\item
3221A project has additional meta info described in Do.prj file
3222\item
3223A project may be dependent on other packages
3224\item
3225A project can be transformed into a package for distribution
3226\item
3227A project can generate one or more executable binaries
3228\end{itemize}
3229\end{itemize}
3230
3231
3232\subsubsection{Module File Organization}
3233
3234The rules of this section are the conventions to organize module files in one package.
3235
3236The file location of a module in a package must match the module/submodule naming hierarchy.
3237The names separated by slash "/" must match the directory levels.
3238If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3239The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3240
3241Here is an example of a package, util.
3242\begin{lstlisting}
3243+ util
3244Do.prj #package description file
3245        heap.do #Case 1: module heap;
3246        list.do #Case 1: mdoule list;
3247        ring.do #Case 1: module ring;
3248        + string #Case 2
3249        impl1.do #module string;
3250        + std
3251        vector.do
3252        list.do
3253        + array #Case 3
3254        array1.do #module std/array;
3255        array2.do #module std/array;
3256        sequence.do #Case 4, module std/sequence;
3257        test.do #Case 5
3258\end{lstlisting}
3259
3260\begin{itemize}
3261\item
3262Case 1: Each individual file implements a module
3263\item
3264Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3265\item
3266Case 3: Put the implementation of a module under the sub-directory; There are several files to
3267implement one module
3268\item
3269Case 4: One file to express one aggregation
3270\item
3271Case 5: The file does not belong to any module; It is used for testing purpose
3272\end{itemize}
3273
3274The example only uses source code, ".do" files, to show the module file organization.
3275Other module packaging formats, like binary, must also follow the same rules.
3276
3277
3278\subsection{Module File Format}
3279
3280\CFA supports different types of module file formats.
3281
3282\begin{itemize}
3283\item
3284Pure source code format: The files should be organized following the previous section's definition.
3285\item
3286IR format (TBD): The \CFA compiler IR format, similar to the source code format
3287\item
3288Binary format, including ".a" static library or ".so" dynamic linkage library
3289\begin{itemize}
3290\item
3291The file's name must match the right level's module name defined in the previous section
3292\item
3293E.g. "util.so" includes all modules for the package util.
3294\item
3295E.g. "string.so" under the package directory to include files belonging to "module string;"
3296\end{itemize}
3297\item.
3298Archive format
3299\begin{itemize}
3300\item
3301The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3302\item
3303E.g. "util.dar" is the whole package for util package including the package direction file
3304\end{itemize}
3305\item
3306Hybrid format
3307\begin{itemize}
3308\item
3309A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3310\item
3311The only limitation is that the names of the files must match the module location names defined in previous section
3312\end{itemize}
3313\end{itemize}
3314Package and Module Locating and the \CFA Language Tooling documentation for more details.
3315
3316
3317\subsection{Packages}
3318
3319A package is synonymous with a library in other languages.
3320The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management.
3321A package is a physical grouping of one or more modules in a directory (an archive file for a directory).
3322The concept of a package is the convention for grouping code, and the contract between the language and the building tool to search for imported modules.
3323
3324
3325\subsubsection{Package Definition}
3326
3327A package is defined by putting a project description file, Do.prj, with one or more modules into a directory.
3328This project description file contains the package's meta data, including package name, author, version, dependences, etc.
3329It should be in the root of the package directory.
3330
3331The modules in the package could be either source code, or compiled binary format.
3332The location of the module files should follow the module name's path.
3333
3334Here is a simple example of the directory structure of a package, core.
3335It contains a module std and several sub-modules under std.
3336\begin{lstlisting}
3337+ core
3338        Do.prj
3339        + std
3340        + io
3341        file.do # module std/io/file;
3342        network.do #module std/io/network;
3343        + container
3344        vector.do #module std/container/vector;
3345        list.do #module std/container/list;
3346\end{lstlisting}
3347
3348
3349\subsubsection{Package Import}
3350
3351Because packages are the places where the building tool looks for modules, there is no code required in the \CFA source file to import a package.
3352In order to use modules in a package, the programmer needs to guide the building tool to locate the right package by 1) Adding the package's parent path into \$DOPATH; or 2) Adding the package dependence into the current project's Do.prj.
3353More details about locating a module in a package are explained in the next section.
3354
3355
3356\subsubsection{Package Versioning}
3357
3358A package must have a version number.
3359The version number is a string.
3360For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3361By convention, a package is stored in a directory named packageName-packageVersion.
3362For example, the util package with version 1.1 is stored in a directory named util-1.1.
3363
3364The project description file can optionally specify the version of the package used in the current project.
3365If not defined, because the version number is a string, and all the different versions for the same package will be sorted in increasing order, the package with the largest version number will be used in the compilation.
3366The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3367
3368
3369\subsection{Module and Package Organization}
3370
3371\CFA has two level of encapsulations, module and package.
3372This section explains the object model of modules, packages and other language concepts.
3373It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3374
3375
3376\subsubsection{Object Model}
3377
3378There are several concepts in Do.
3379\begin{itemize}
3380\item
3381File: a \CFA source file
3382\item
3383Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3384\item
3385Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc.
3386\item
3387Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3388\end{itemize}
3389
3390The following rules summarize the object model of all the above concepts:
3391\begin{itemize}
3392\item
3393A module contains one or more files
3394\begin{itemize}
3395\item
3396One file can only belong to one module
3397\item
3398A module has its name and interfaces exported
3399\item
3400A file without a module declaration at the beginning belongs to the global module
3401\end{itemize}
3402\item
3403A package contains one or more modules
3404\begin{itemize}
3405\item
3406A package has additional meta info described in Do.prj file
3407\item
3408A package may be dependent on other packages.
3409\end{itemize}
3410\item
3411A project contains one or more modules in its source code
3412\begin{itemize}
3413\item
3414A project has additional meta info described in Do.prj file
3415\item
3416A project may be dependent on other packages
3417\item
3418A project can be transformed into a package for distribution
3419\item
3420A project can generate one or more executable binaries
3421\end{itemize}
3422\end{itemize}
3423
3424
3425\subsubsection{Module File Organization}
3426
3427The rules of this section are the conventions to organize module files in one package.
3428
3429The file location of a module in a package must match the module/submodule naming hierarchy.
3430The names separated by slash "/" must match the directory levels.
3431If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3432The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3433
3434Here is an example of a package, util.
3435\begin{lstlisting}
3436+ util
3437        Do.prj #package description file
3438        heap.do #Case 1: module heap;
3439        list.do #Case 1: mdoule list;
3440        ring.do #Case 1: module ring;
3441        + string #Case 2
3442        impl1.do #module string;
3443        + std
3444        vector.do
3445        list.do
3446        + array #Case 3
3447        array1.do #module std/array;
3448        array2.do #module std/array;
3449        sequence.do #Case 4, module std/sequence;
3450        test.do #Case 5
3451\end{lstlisting}
3452
3453
3454\begin{itemize}
3455\item
3456Case 1: Each individual file implements a module
3457\item
3458Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3459\item
3460Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module
3461\item
3462Case 4: One file to express one aggregation
3463\item
3464Case 5: The file does not belong to any module; It is used for testing purpose
3465\end{itemize}
3466
3467The example only uses source code, ".do" files, to show the module file organization.
3468Other module packaging formats, like binary, must also follow the same rules.
3469
3470
3471\subsubsection{Module File Format}
3472
3473\CFA supports different types of module file formats.
3474
3475\begin{itemize}
3476\item
3477Pure source code format: The files should be organized following the previous section's definition.
3478\item
3479IR format (TBD): The \CFA compiler IR format, similar to the source code format
3480\item
3481Binary format, including ".a" static library or ".so" dynamic linkage library
3482\begin{itemize}
3483\item
3484The file's name must match the right level's module name defined in the previous section
3485\item
3486E.g. "util.so" includes all modules for the package util.
3487\item
3488E.g. "string.so" under the package directory to include files belonging to "module string;"
3489\end{itemize}
3490\item
3491Archive format
3492\begin{itemize}
3493\item
3494The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3495\item
3496E.g. "util.dar" is the whole package for util package including the package direction file
3497\end{itemize}
3498\item
3499Hybrid format
3500\begin{itemize}
3501\item
3502A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3503\item
3504The only limitation is that the names of the files must match the module location names defined in previous section
3505\end{itemize}
3506\end{itemize}
3507
3508
3509\subsection{Package and Module Locating}
3510
3511The high-level build tools provided by \CFA will handle finding a package in your local filesystem or retrieving it from a repository if necessary, building it if necessary, and linking with it.
3512If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries.
3513
3514When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order:
3515
3516\begin{enumerate}
3517\item
3518This source file's directory tree, which is typically the project's src directory
3519\item
3520All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory
3521\item
3522The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable
3523\item
3524The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory
3525\item
3526If one dependent package is still not found, the builder tool will automatically retrieve it from the repository defined in the SDK installation's configuration, and store it in the SDK's pkg directory
3527\end{enumerate}
3528
3529The module found first in a package will shadow the modules with the same name in the later packages in the search sequence.
3530
3531
3532\subsubsection{Dependent Package}
3533
3534Dependent packages are those packages containing modules that the current project's source code will import from.
3535Dependent packages are defined implicitly or explicitly in one \CFA project.
3536All of the packages under the current project's pkg directory are implicitly dependent packages.
3537For others, the dependent packages must be defined in the project's Do.prj file.
3538
3539
3540\subsubsection{Package and Module Locating Example}
3541
3542\begin{lstlisting}
3543# A project's source code tree
3544
3545--------------------------------------
3546
3547+ testProject
3548        Do.prj
3549        + src
3550        main.do
3551        + pkg
3552        + security-1.1
3553        Do.prj
3554        security.do #module security
3555
3556--------------------------------------
3557
3558# Do.prj
3559
3560--------------------------------------
3561
3562[dependences]
3563std
3564util = "0.2"
3565
3566--------------------------------------
3567
3568# main.do
3569
3570---------------------------------------
3571
3572import security;
3573import std/vector;
3574import container;
3575
3576----------------------------------------
3577\end{lstlisting}
3578
3579
3580\begin{lstlisting}
3581# pkg directory's source code tree
3582
3583-----------------------------------------
3584
3585+ pkg
3586        + std-1.0
3587        Do.prj
3588        vector.do #module std/vector;
3589        queue.do #module std/queue;
3590        + std-1.1
3591        Do.prj
3592        vector.do #module std/vector;
3593        queue.do #module std/queue;
3594        list.do #module std/list;
3595        + util-0.1
3596        Do.prj
3597        container.do #module container;
3598        + security-1.0
3599        security.do #module security;
3600------------------------------------------
3601\end{lstlisting}
3602
3603
3604During the compiling of main.do file import security;
3605The security module appears in both the local security-1.1 package, and the global security-1.0 package.
3606According to the locating sequence, the local security module in security-1.1 will be used.
3607And because the security-1.1 package is under local's pkg directory.
3608No dependence description is required in the project Do.prj file.
3609
3610import std/vector;
3611
3612The std/vector package appears in two different versions' packages in the global path and the project dependence doesn't specify the version. std-1.1 is used in this case.
3613
3614import container;
3615
3616The Do.prj specifies the version 0.2 should be used to locate container module from util package but only version 0.1 is available in the local file system.
3617The builder tool then will try to retrieve it from the web and store it in the global pkg directory.
3618After that, the container module from the newly downloaded package will be used in the compilation.
3619\end{comment}
3620
3621
3622\section{Comparison with Other Languages}
3623
3624\CFA is one of many languages that attempts to improve upon C.
3625In developing \CFA, many other languages were consulted for ideas, constructs, and syntax.
3626Therefore, it is important to show how these languages each compare with Do.
3627In this section, \CFA is compared with what the writers of this document consider to be the closest competitors of Do: \Index*[C++]{\CC}, \Index*{Go}, \Index*{Rust}, and \Index*{D}.
3628
3629
3630\subsection[Comparing Key Features of CFA]{Comparing Key Features of \CFA}
3631
3632
3633{% local change to lstlising to reduce font size
3634
3635
3636\lstset{basicstyle=\linespread{0.9}\sf\relsize{-2}}
3637
3638
3639\subsubsection{Constructors and Destructors}
3640
3641\begin{flushleft}
3642\begin{tabular}{@{}l|l|l|l@{}}
3643\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3644\hline
3645\begin{lstlisting}
3646struct Line {
3647        float lnth;
3648}
3649// default constructor
3650void ?{}( Line * l ) {
3651        l->lnth = 0.0;
3652        sout | "default" | endl;
3653}
3654
3655
3656// constructor with length
3657void ?{}( Line * l, float lnth ) {
3658        l->lnth = lnth;
3659        sout | "lnth" | l->lnth | endl;
3660
3661}
3662
3663// destructor
3664void ^?() {
3665        sout | "destroyed" | endl;
3666        l.lnth = 0.0;
3667}
3668
3669// usage
3670Line line1;
3671Line line2 = { 3.4 };
3672\end{lstlisting}
3673&
3674\begin{lstlisting}[language=C++]
3675class Line {
3676        float lnth;
3677
3678        // default constructor
3679        Line() {
3680                cout << "default" << endl;
3681                lnth = 0.0;
3682        }
3683
3684
3685        // constructor with lnth
3686        Line( float l ) {
3687                cout << "length " << length
3688                         << endl;
3689                length = l;
3690        }
3691
3692        // destructor
3693        ~Line() {
3694                cout << "destroyed" << endl;
3695                length = 0.0;
3696        }
3697}
3698// usage
3699Line line1;
3700Line line2( 3.4 );
3701\end{lstlisting}
3702&
3703\begin{lstlisting}[language=Golang]
3704type Line struct {
3705        length float32
3706}
3707// default constructor
3708func makeLine() Line {
3709        fmt.PrintLn( "default" )
3710        return Line{0.0}
3711}
3712
3713
3714// constructor with length
3715func makeLine( length float32 ) Line {
3716        fmt.Printf( "length %v", length )
3717
3718        return Line{length}
3719}
3720
3721// no destructor
3722
3723
3724
3725
3726
3727// usage
3728line1 := makeLine()
3729line2 := makeLine( 3.4 )
3730\end{lstlisting}
3731&
3732\begin{lstlisting}
3733struct Line {
3734        length: f32
3735}
3736// default constructor
3737impl Default for Line {
3738        fn default () -> Line {
3739                println!( "default" );
3740                Line{ length: 0.0 }
3741        }
3742}
3743// constructor with length
3744impl Line {
3745        fn make( len: f32 ) -> Line {
3746                println!( "length: {}", len );
3747                Line{ length: len }
3748        }
3749}
3750// destructor
3751impl Drop for Line {
3752        fn drop( &mut self ) {
3753                self.length = 0.0
3754        }
3755}
3756// usage
3757let line1:Line = Default::default();
3758Line line2( 3.4 );
3759\end{lstlisting}
3760\end{tabular}
3761\end{flushleft}
3762
3763
3764\subsubsection{Operator Overloading}
3765
3766\begin{flushleft}
3767\begin{tabular}{@{}l|l|l|l@{}}
3768\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3769\hline
3770\begin{lstlisting}
3771struct Cpx {
3772        double re, im;
3773};
3774// overload addition operator
3775Cpx ?+?( Cpx l, const Cpx r ) {
3776        return (Cpx){l.re+l.im, l.im+r.im};
3777}
3778Cpx a, b, c;
3779c = a + b;
3780\end{lstlisting}
3781&
3782\begin{lstlisting}
3783struct Cpx {
3784        double re, im;
3785};
3786// overload addition operator
3787Cpx operator+( Cpx l, const Cpx r ) {
3788        return (Cpx){l.re+l.im, l.im+r.im};
3789}
3790Cpx a, b, c;
3791c = a + b;
3792\end{lstlisting}
3793&
3794\begin{lstlisting}
3795// no operator overloading
3796
3797
3798
3799
3800
3801
3802
3803\end{lstlisting}
3804&
3805\begin{lstlisting}
3806struct Cpx {
3807        re: f32,
3808        im: f32
3809}
3810// overload addition operator
3811impl Add for Cpx {
3812        type Output = Cpx
3813        fn add(self, r: Cpx) -> Cpx {
3814                let mut res = Cpx{re: 0.0, im: 0.0};
3815                res.re = self.re + r.re;
3816                res.im = self.im + r.im;
3817                return res
3818        }
3819}
3820let (a, b, mut c) = ...;
3821c = a + b
3822\end{lstlisting}
3823\end{tabular}
3824\end{flushleft}
3825
3826
3827\subsubsection{Calling C Functions}
3828
3829\begin{flushleft}
3830\begin{tabular}{@{}l|l|l@{}}
3831\multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}   \\
3832\hline
3833\begin{lstlisting}[boxpos=t]
3834extern "C" {
3835#include <sys/types.h>
3836#include <sys/stat.h>
3837#include <unistd.h>
3838}
3839size_t fileSize( const char *path ) {
3840        struct stat s;
3841        stat(path, &s);
3842        return s.st_size;
3843}
3844\end{lstlisting}
3845&
3846\begin{lstlisting}[boxpos=t]
3847/*
3848#cgo
3849#include <sys/types.h>
3850#include <sys/stat.h>
3851#include <unistd.h>
3852*/
3853import "C"
3854import "unsafe"
3855
3856func fileSize(path string) C.size_t {
3857        var buf C.struct_stat
3858        c_string := C.CString(path)
3859        C.stat(p, &buf)
3860        C.free(unsafe.Pointer(c_string))
3861        return buf._st_size
3862}
3863\end{lstlisting}
3864&
3865\begin{lstlisting}[boxpos=t]
3866use libc::{c_int, size_t};
3867// translated from sys/stat.h
3868#[repr(C)]
3869struct stat_t {
3870        ...
3871        st_size: size_t,
3872        ...
3873}
3874#[link(name = "libc")]
3875extern {
3876        fn stat(path: *const u8,
3877        buf: *mut stat_t) -> c_int;
3878}
3879fn fileSize(path: *const u8) -> size_t
3880{
3881        unsafe {
3882                let mut buf: stat_t = uninit();
3883                stat(path, &mut buf);
3884                buf.st_size
3885        }
3886}
3887\end{lstlisting}
3888\end{tabular}
3889\end{flushleft}
3890
3891
3892\subsubsection{Generic Functions}
3893
3894\begin{flushleft}
3895\begin{tabular}{@{}l|l|l|l@{}}
3896\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3897\hline
3898\begin{lstlisting}
3899generic(type T, type N |
3900        { int ?<?(N, N); })
3901T *maximize(N (*f)(const T&),
3902        int n, T *a) {
3903        T *bestX = NULL;
3904        N bestN;
3905        for (int i = 0; i < n; i++) {
3906        N curN = f(a[i]);
3907        if (bestX == NULL ||
3908        curN > bestN) {
3909        bestX = &a[i]; bestN = curN;
3910        }
3911        }
3912        return bestX;
3913}
3914
3915string *longest(int n, string *p)
3916{
3917        return maximize(length, n, p);
3918}
3919\end{lstlisting}
3920&
3921\begin{lstlisting}
3922template<typename T, typename F>
3923T *maximize(const F &f,
3924        int n, T *a) {
3925        typedef decltype(f(a[0])) N;
3926        T *bestX = NULL;
3927        N bestN;
3928        for (int i = 0; i < n; i++) {
3929        N curN = f(a[i]);
3930        if (bestX == NULL || curN > bestN)
3931        {
3932        bestX = &a[i]; bestN = curN;
3933        }
3934        }
3935        return bestX;
3936}
3937
3938string *longest(int n, string *p) {
3939        return maximize(
3940        [](const string &s) {
3941        return s.length();
3942        }, n, p);
3943}
3944\end{lstlisting}
3945&
3946\begin{lstlisting}
3947// Go does not support generics!
3948func maximize(
3949        gt func(interface{}, interface{}) bool,
3950        f func(interface{}) interface{},
3951        a []interface{}) interface{} {
3952        var bestX interface{} = nil
3953        var bestN interface{} = nil
3954        for _, x := range a {
3955        curN := f(x)
3956        if bestX == nil || gt(curN, bestN)
3957        {
3958        bestN = curN
3959        bestX = x
3960        }
3961        }
3962        return bestX
3963}
3964
3965func longest(
3966        a []interface{}) interface{} {
3967        return maximize(
3968        func(a, b interface{}) bool {
3969        return a.(int) > b.(int) },
3970        func(s interface{}) interface{} {
3971        return len(s.(string)) },
3972        a).(string)
3973}
3974\end{lstlisting}
3975&
3976\begin{lstlisting}
3977use std::cmp::Ordering;
3978
3979fn maximize<N: Ord + Copy, T, F:
3980Fn(&T) -> N>(f: F, a: &Vec<T>) ->
3981Option<&T> {
3982        let mut best_x: Option<&T> = None;
3983        let mut best_n: Option<N> = None;
3984        for x in a {
3985        let n = f(x);
3986        if (match best_n { None => true,
3987        Some(bn) =>
3988        n.cmp(&bn) == Ordering::Greater })
3989        {
3990        best_x = Some(x);
3991        best_n = Some(n);
3992        }
3993        }
3994        return best_x
3995}
3996
3997fn longest(a: &Vec<String>) ->
3998        Option<&String> {
3999        return
4000        maximize(|x: &String| x.len(), a)
4001}
4002\end{lstlisting}
4003\end{tabular}
4004\end{flushleft}
4005
4006
4007\begin{comment}
4008\subsubsection{Modules / Packages}
4009
4010\begin{lstlisting}
4011\CFA
4012\CC
4013
4014
4015module example/M;
4016
4017export int inc(int val) {
4018        return val + 1;
4019}
4020
4021
4022
4023
4024--------------------------------------
4025//Use the module in another file
4026import example/M;
4027int main() {
4028        print(M.inc(100));
4029        return 0;
4030}
4031// Using \CC17 module proposal
4032
4033module example.M;
4034
4035export {
4036        int inc(int val);
4037}
4038
4039int inc(inv val) {
4040        return val + 1;
4041}
4042--------------------------------------
4043// Use the module in another file
4044import example.M;
4045int main() {
4046        cout << inc(100) << endl;
4047        return 0;
4048}
4049
4050Go
4051Rust
4052package example/M;
4053
4054func Inc(val int32) int32 {
4055        // Capitalization indicates exported
4056        return val + 100
4057}
4058
4059
4060--------------------------------------
4061//Use the package in another file
4062package main
4063import .fmt.
4064import "example/M"
4065
4066func main() int32 {
4067        fmt.Printf(.%v., M.Inc(100))
4068}
4069pub mod example {
4070        pub mod M {
4071        pub inc(val i32) -> i32 {
4072        return val + 100;
4073        }
4074        }
4075}
4076
4077--------------------------------------
4078//Use the module in another file
4079use example::M;
4080
4081
4082
4083fn main() {
4084        println!(.{}., M::inc(100));
4085}
4086\end{lstlisting}
4087\end{comment}
4088
4089
4090\subsubsection{Parallel Tasks}
4091
4092\begin{flushleft}
4093\begin{tabular}{@{}l|l|l|l@{}}
4094\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4095\hline
4096\begin{lstlisting}
4097task Nonzero {
4098        int *data;
4099        int start;
4100        int end;
4101        int* res;
4102};
4103
4104void ?{}(Nonzero &a, int d[], int s,
4105        int e, int* subres) {
4106        // constructor
4107        a.data = d;
4108        a.start = s;
4109        a.end = e;
4110        a.res = subres;
4111}
4112
4113// implicitly spawn thread here
4114void ?()(NonzeroCounter &a) {
4115        int i;
4116        int nonzero = 0;
4117        for (i=start; c<end; ++i) {
4118        if(a.data[i]!=0){ nonzero++;}
4119        }
4120        *a.res = nonzero;
4121}
4122
4123int main() {
4124        int sz = ...
4125        int data[sz] = ...;
4126        int r1 = 0, r2=0;
4127        int res;
4128        { // create a scope for Nonzero
4129        Nonzero n1{data, 0, sz/2, &n1};
4130        Nonzero n2{data, sz/2, sz, &n2};
4131        n1();//spawn
4132        n2();//spawn
4133        }
4134        res = r1+r2;
4135        return res;
4136}
4137\end{lstlisting}
4138&
4139\begin{lstlisting}
4140#include <thread>
4141#include <mutex>
4142
4143std::mutex m;
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156void task(const vector<int>&v,
4157        int* res, size_t s,
4158        size_t e) {
4159        int non_zero = 0;
4160        for(size_t i = s; i < e; ++i){
4161        if(v[i]!=0) { non_zero++;}
4162        }
4163        std::unique_lock<mutex> lck {m};
4164        *res += non_zero;
4165}
4166
4167int main() {
4168        vector<int> data = ...; //data
4169        int res = 0;
4170        std::thread t1 {task, ref(data),
4171        &res, 0,
4172        data.size()/2};
4173        std::thread t2 {task, ref(data),
4174        &res, data.size()/2,
4175        data.size()};
4176        t1.join();
4177        t2.join();
4178        return res;
4179}
4180\end{lstlisting}
4181&
4182\begin{lstlisting}
4183package main
4184
4185import "fmt"
4186
4187func nonzero(data []int, c chan int) {
4188        nz := 0
4189        for _, v:=range data {
4190        if(v!=0) { nz := nz+1 }
4191        }
4192        c <- nz
4193}
4194
4195func main() {
4196        sz := ...
4197        data := make([]int, sz)
4198        ... // data init
4199        go nonzero(data[:len(data)/2], c)
4200        go nonzero(data[len(data)/2:], c)
4201        n1, n2 := <-c, <-c
4202        res := n1 + n2
4203        fmt.Println(res)
4204}
4205\end{lstlisting}
4206&
4207\begin{lstlisting}
4208use std::thread;
4209use std::sync:mpsc::channel;
4210
4211fn main() {
4212        let sz = ...;
4213        let mut data:Vec<i32> =
4214        Vec::with_capacity(sz as usize);
4215        ... //init data
4216        let (tx, rx) = channel();
4217        for i in 0..1 {
4218        let tx = tx.clone();
4219        let data = data.clone()
4220        thread::spawn(move|| {
4221        let mut nz := 0;
4222        let mut s = 0;
4223        let mut e = sz / 2;
4224        if i == 1 {
4225        s = sz/2;
4226        e = data.len();
4227        }
4228        for i in s..(e - 1) {
4229        if data[i] != 0 (
4230        nz = nz + 1
4231        }
4232        }
4233        tx.send(nz).unwrap();
4234        });
4235        }
4236        let res = rx.recv().unwrap() +
4237        rx.recv().unwrap();
4238        println!(.{}., res);
4239}
4240\end{lstlisting}
4241\end{tabular}
4242\end{flushleft}
4243
4244}% local change to lstlising to reduce font size
4245
4246
4247\subsection{Summary of Language Comparison}
4248
4249
4250\subsubsection[C++]{\CC}
4251
4252\Index*[C++]{\CC} is a general-purpose programming language.
4253It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia)
4254
4255The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do.
4256\CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data.
4257\CFA uses modules instead to perform these same tasks.
4258Classes in \CC also enable inheritance among types.
4259Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility.
4260There are many studies and articles comparing inheritance and composition (or is-a versus has-a relationships), so we will not go into more detail here (Venners, 1998) (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering , 2012).
4261
4262Overloading in \CFA is very similar to overloading in \CC, with the exception of the additional use, in \CFA, of the return type to differentiate between overloaded functions.
4263References and exceptions in \CFA are heavily based on the same features from \CC.
4264The mechanism for interoperating with C code in \CFA is also borrowed from \CC.
4265
4266Both \CFA and \CC provide generics, and the syntax is quite similar.
4267The key difference between the two, is that in \CC templates are expanded at compile time for each type for which the template is instantiated, while in \CFA, function pointers are used to make the generic fully compilable.
4268This means that a generic function can be defined in a compiled library, and still be used as expected from source.
4269
4270
4271\subsubsection{Go}
4272
4273\Index*{Go}, also commonly referred to as golang, is a programming language developed at Google in 2007 [.].
4274It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type
4275safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia)
4276
4277Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned.
4278Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction.
4279Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse.
4280Both languages also include built-in light weight, user level threading concurrency features that attempt to simplify the effort and thought process required for writing parallel programs while maintaining high performance.
4281
4282Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks.
4283\CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection.
4284This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead.
4285
4286
4287\subsubsection{Rust}
4288
4289\Index*{Rust} is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research.
4290It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles.
4291
4292The primary focus of Rust is in safety, especially in concurrent programs.
4293To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety.
4294This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead.
4295
4296Aside from those key differences, Rust and \CFA also have several similarities.
4297Both languages support no overhead interoperability with C and have minimal runtimes.
4298Both languages support inheritance and polymorphism through the use of interfaces (traits).
4299
4300
4301\subsubsection{D}
4302
4303The \Index*{D} programming language is an object-oriented, imperative, multi-paradigm system programming
4304language created by Walter Bright of Digital Mars and released in 2001. [.]
4305Though it originated as a re-engineering of \CC, D is a distinct language, having redesigned some core \CC features while also taking inspiration from other languages, notably \Index*{Java}, \Index*{Python}, Ruby, C\#, and Eiffel.
4306
4307D and \CFA both start with C and add productivity features.
4308The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces.
4309D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces.
4310Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates.
4311D does not have any built-in concurrency constructs in the
4312language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency.
4313
4314
4315\appendix
4316
4317
4318\section{Incompatible}
4319
4320The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
4321
4322\begin{enumerate}
4323\item
4324\begin{description}
4325\item[Change:] add new keywords \\
4326New keywords are added to \CFA.
4327\item[Rationale:] keywords added to implement new semantics of \CFA.
4328\item[Effect on original feature:] change to semantics of well-defined feature. \\
4329Any ISO C programs using these keywords as identifiers are invalid \CFA programs.
4330\item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism:
4331\begin{lstlisting}
4332int `otype` = 3;                                // make keyword an indentifier
4333double `choose` = 3.5;
4334\end{lstlisting}
4335Programs can be converted automatically by enclosing keyword identifiers in backquotes, and the backquotes can be remove later when the identifier name is changed.
4336Clashes in C system libraries (include files) can be handled automatically using preprocessor, ©#include_next© and ©-Ifilename©:
4337\begin{lstlisting}
4338// include file uses the CFA keyword "otype".
4339#if ! defined( otype )                  // nesting ?
4340#define otype `otype`
4341#define __CFA_BFD_H__
4342#endif // ! otype
4343
4344#include_next <bfd.h>                   // must have internal check for multiple expansion
4345
4346#if defined( otype ) && defined( __CFA_BFD_H__ )        // reset only if set
4347#undef otype
4348#undef __CFA_BFD_H__
4349#endif // otype && __CFA_BFD_H__
4350\end{lstlisting}
4351\item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare.
4352\end{description}
4353
4354\item
4355\begin{description}
4356\item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading:
4357\begin{lstlisting}
4358int rtn( int i );
4359int rtn( char c );
4360rtn( 'x' );                                             // programmer expects 2nd rtn to be called
4361\end{lstlisting}
4362\item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first.
4363In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character.
4364\begin{lstlisting}
4365sout | 'x' | " " | (int)'x' | endl;
4366x 120
4367\end{lstlisting}
4368Having to cast ©'x'© to ©char© is non-intuitive.
4369\item[Effect on original feature:] change to semantics of well-defined feature that depend on:
4370\begin{lstlisting}
4371sizeof( 'x' ) == sizeof( int )
4372\end{lstlisting}
4373no long work the same in \CFA programs.
4374\item[Difficulty of converting:] simple
4375\item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©.
4376\end{description}
4377
4378\item
4379\begin{description}
4380\item[Change:] make string literals ©const©:
4381\begin{lstlisting}
4382char * p = "abc";                               // valid in C, deprecated in §\CFA§
4383char * q = expr ? "abc" : "de"; // valid in C, invalid in §\CFA§
4384\end{lstlisting}
4385The type of a string literal is changed from ©[] char© to ©const [] char©.
4386Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©.
4387\item[Rationale:] This change is a safety issue:
4388\begin{lstlisting}
4389char * p = "abc";
4390p[0] = 'w';                                             // segment fault or change constant literal
4391\end{lstlisting}
4392The same problem occurs when passing a string literal to a routine that changes its argument.
4393\item[Effect on original feature:] change to semantics of well-defined feature.
4394\item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©.
4395\item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare.
4396\end{description}
4397
4398\item
4399\begin{description}
4400\item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope:
4401\begin{lstlisting}
4402int i;                                                  // forward definition
4403int *j = ®&i®;                                  // forward reference, valid in C, invalid in §\CFA§
4404int i = 0;                                              // definition
4405\end{lstlisting}
4406is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed.
4407This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example,
4408\begin{lstlisting}
4409struct X { int i; struct X *next; };
4410static struct X a;                              // forward definition
4411static struct X b = { 0, ®&};        // forward reference, valid in C, invalid in §\CFA§
4412static struct X a = { 1, &b };  // definition
4413\end{lstlisting}
4414\item[Rationale:] avoids having different initialization rules for builtin types and userdefined types.
4415\item[Effect on original feature:] change to semantics of well-defined feature.
4416\item[Difficulty of converting:] the initializer for one of a set of mutually-referential file-local static objects must invoke a routine call to achieve the initialization.
4417\item[How widely used:] seldom
4418\end{description}
4419
4420\item
4421\begin{description}
4422\item[Change:] have ©struct© introduce a scope for nested types
4423In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing
4424Example:
4425\begin{lstlisting}
4426enum ®Colour® { R, G, B, Y, C, M };
4427struct Person {
4428        enum ®Colour® { R, G, B };      // nested type
4429        struct Face {                           // nested type
4430                ®Colour® Eyes, Hair;            // type defined outside (1 level)
4431        };
4432        ß.ß®Colour® shirt;                              // type defined outside (top level)
4433        ®Colour® pants;                         // type defined same level
4434        Face looks[10];                         // type defined same level
4435};
4436®Colour® c = R;                                 // type/enum defined same level
4437Personß.ß®Colour® pc = Personß.ßR;      // type/enum defined inside
4438Personß.ßFace pretty;                           // type defined inside
4439\end{lstlisting}
4440\item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism.
4441\item[Effect on original feature:] change to semantics of well-defined feature.
4442\item[Difficulty of converting:] Semantic transformation.
4443\item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version.
4444
4445\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC}.
4446Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''.
4447Given that nested types in C are equivalent to not using them, i.e., they are essentially useless, it is unlikely there are any realistic usages that break because of this incompatibility.
4448\end{description}
4449
4450\item
4451\begin{description}
4452\item[Change:] In C++, the name of a nested class is local to its enclosing class.
4453\item[Rationale:] C++ classes have member functions which require that classes establish scopes.
4454\item[Difficulty of converting:] Semantic transformation. To make the struct type name visible in the scope of the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing struct is defined. Example:
4455\begin{lstlisting}
4456struct Y; // struct Y and struct X are at the same scope
4457struct X {
4458struct Y { /* ... */ } y;
4459};
4460\end{lstlisting}
4461All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of the enclosing struct could be exported to the scope of the enclosing struct.
4462Note: this is a consequence of the difference in scope rules, which is documented in 3.3.
4463\item[How widely used:] Seldom.
4464\end{description}
4465
4466\item
4467\begin{description}
4468\item[Change:] comma expression is disallowed as subscript
4469\item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new styple arrays.
4470\item[Effect on original feature:] change to semantics of well-defined feature.
4471\item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]©
4472\item[How widely used:] seldom.
4473\end{description}
4474\end{enumerate}
4475
4476
4477\section{I/O Library}
4478\label{s:IOLibrary}
4479\index{input/output library}
4480
4481The goal for the \CFA I/O is to make I/O as simple as possible in the common cases, while fully supporting polmorphism and user defined types in a consistent way.
4482The common case is printing out a sequence of variables separated by whitespace.
4483\begin{quote2}
4484\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
4485\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{\CC}}      \\
4486\begin{lstlisting}
4487int x = 0, y = 1, z = 2;
4488®sout® ®|® x ®|® y ®|® z ®| endl®;
4489\end{lstlisting}
4490&
4491\begin{lstlisting}
4492
4493cout << x << " " << y << " " << z << endl;
4494\end{lstlisting}
4495\end{tabular}
4496\end{quote2}
4497The \CFA form has half as many characters as the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators.
4498
4499The logical-or operator is used because it is the lowest-priority overloadable operator, other than assignment.
4500Therefore, fewer output expressions require parenthesis.
4501\begin{quote2}
4502\begin{tabular}{@{}ll@{}}
4503\textbf{\CFA:}
4504&
4505\begin{lstlisting}
4506sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
4507\end{lstlisting}
4508\\
4509\textbf{\CC:}
4510&
4511\begin{lstlisting}
4512cout << x * 3 << y + 1 << (z << 2) << (x == y) << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
4513\end{lstlisting}
4514\end{tabular}
4515\end{quote2}
4516Finally, the logical-or operator has a link with the Shell pipe-operator for moving data, although data flows in the opposite direction.
4517
4518The implicit seperator\index{I/O separator} character (space/blank) is a separator not a terminator.
4519The rules for implicitly adding the separator are:
4520\begin{enumerate}
4521\item
4522A seperator does not appear at the start or end of a line.
4523\begin{lstlisting}[belowskip=0pt]
4524sout | 1 | 2 | 3 | endl;
4525\end{lstlisting}
4526\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
45271 2 3
4528\end{lstlisting}
4529\item
4530A seperator does not appear before or after a character literal or variable.
4531\begin{lstlisting}
4532sout | '1' | '2' | '3' | endl;
4533123
4534\end{lstlisting}
4535\item
4536A seperator does not appear before or after a null (empty) C string
4537\begin{lstlisting}
4538sout | 1 | "" | 2 | "" | 3 | endl;
4539123
4540\end{lstlisting}
4541which is a local mechanism to disable insertion of the separator character.
4542\item
4543A seperator does not appear before a C string starting with the (extended) \Index{ASCII}\index{ASCII!extended} characters: \lstinline[mathescape=off]@([{$£¥¡¿«@
4544%$
4545\begin{lstlisting}[mathescape=off]
4546sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x $" | 4 | "x £" | 5 | "x ¥" | 6 | "x ¡" | 7 | "x ¿" | 8 | "x «" | 9 | endl;
4547\end{lstlisting}
4548%$
4549\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4550x (1 x [2 x {3 x $4 x £5 x ¥6 x ¡7 x ¿8 x «9
4551\end{lstlisting}
4552%$
4553\item
4554A seperator does not appear after a C string ending with the (extended) \Index{ASCII}\index{ASCII!extended} characters: ©,.:;!?)]}%¢»©
4555\begin{lstlisting}[belowskip=0pt]
4556sout | 1 | ", x" | 2 | ". x" | 3 | ": x" | 4 | "; x" | 5 | "! x" | 6 | "? x" | 7 | ") x" | 8 | "] x" | 9 | "} x"
4557         | 10 | "% x" | 11 | "¢ x" | 12 | "» x" | endl;
4558\end{lstlisting}
4559\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
45601, x 2. x 3: x 4; x 5! x 6? x 7) x 8] x 9} x 10% x 11¢ 12»
4561\end{lstlisting}
4562\item
4563A seperator does not appear before or after a C string begining/ending with the \Index{ASCII} quote or whitespace characters: \lstinline[showspaces=true]@`'" \t\v\f\r\n@
4564\begin{lstlisting}[belowskip=0pt]
4565sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x" | "x " | 4 | " x" | "x\t" | 1 | "\tx" | endl;
4566\end{lstlisting}
4567\begin{lstlisting}[mathescape=off,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt]
4568x`1`x'2'x"3"x x 4 x x   1       x
4569\end{lstlisting}
4570\end{enumerate}
4571The following \CC-style \Index{manipulator}s allow further control over implicit seperation.
4572\begin{lstlisting}[mathescape=off,belowskip=0pt]
4573sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
4574\end{lstlisting}
4575\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4576 1 2 3
4577\end{lstlisting}
4578\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4579sout | 1 | sepOff | 2 | 3 | endl;                       // turn off implicit separator temporarily
4580\end{lstlisting}
4581\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
458212 3
4583\end{lstlisting}
4584\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4585sout | sepDisable | 1 | 2 | 3 | endl;           // turn off implicit separation, affects all subsequent prints
4586\end{lstlisting}
4587\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4588123
4589\end{lstlisting}
4590\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4591sout | 1 | sepOn | 2 | 3 | endl;                        // turn on implicit separator temporarily
4592\end{lstlisting}
4593\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
45941 23
4595\end{lstlisting}
4596\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4597sout | sepEnable | 1 | 2 | 3 | endl;            // turn on implicit separation, affects all subsequent prints
4598\end{lstlisting}
4599\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4600 1 2 3
4601\end{lstlisting}
4602\begin{lstlisting}[mathescape=off,aboveskip=0pt,aboveskip=0pt,belowskip=0pt]
4603sepSet( sout, ", $" );                                          // change separator from " " to ", $"
4604sout | 1 | 2 | 3 | endl;
4605\end{lstlisting}
4606%$
4607\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt]
46081, $2, $3
4609\end{lstlisting}
4610%$
4611\begin{comment}
4612#include <fstream>
4613
4614int main() {
4615        int x = 3, y = 5, z = 7;
4616        sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
4617        sout | 1 | 2 | 3 | endl;
4618        sout | '1' | '2' | '3' | endl;
4619        sout | 1 | "" | 2 | "" | 3 | endl;
4620        sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x $" | 4 | "x £" | 5 | "x ¥" | 6 | "x ¡" | 7 | "x ¿" | 8 | "x «" | 9 | endl;
4621        sout | 1 | ", x" | 2 | ". x" | 3 | ": x" | 4 | "; x" | 5 | "! x" | 6 | "? x" | 7 | ") x" | 8 | "] x" | 9 | "} x"
4622                 | 10 | "% x" | 11 | "¢ x" | 12 | "» x" | endl;
4623        sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x" | "x " | 4 | " x" | "x\t" | 1 | "\tx" | endl;
4624        sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
4625        sout | 1 | sepOff | 2 | 3 | endl;                       // turn off implicit separator temporarily
4626        sout | sepDisable | 1 | 2 | 3 | endl;           // turn off implicit separation, affects all subsequent prints
4627        sout | 1 | sepOn | 2 | 3 | endl;                        // turn on implicit separator temporarily
4628        sout | sepEnable | 1 | 2 | 3 | endl;            // turn on implicit separation, affects all subsequent prints
4629        sepSet( sout, ", $" );                                          // change separator from " " to ", $"
4630        sout | 1 | 2 | 3 | endl;
4631
4632}
4633
4634// Local Variables: //
4635// tab-width: 4 //
4636// End: //
4637\end{comment}
4638%$
4639
4640
4641\section{Standard Library}
4642\label{s:StandardLibrary}
4643
4644The goal of the \CFA standard-library is to wrap many of the existing C library-routines that are explicitly polymorphic into implicitly polymorphic versions.
4645
4646
4647\subsection{malloc}
4648
4649\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4650forall( otype T ) T * malloc( void );§\indexc{malloc}§
4651forall( otype T ) T * malloc( char fill );
4652forall( otype T ) T * malloc( T * ptr, size_t size );
4653forall( otype T ) T * malloc( T * ptr, size_t size, unsigned char fill );
4654forall( otype T ) T * calloc( size_t nmemb );§\indexc{calloc}§
4655forall( otype T ) T * realloc( T * ptr, size_t size );§\indexc{ato}§
4656forall( otype T ) T * realloc( T * ptr, size_t size, unsigned char fill );
4657
4658forall( otype T ) T * aligned_alloc( size_t alignment );§\indexc{ato}§
4659forall( otype T ) T * memalign( size_t alignment );             // deprecated
4660forall( otype T ) int posix_memalign( T ** ptr, size_t alignment );
4661
4662forall( otype T ) T * memset( T * ptr, unsigned char fill ); // use default value '\0' for fill
4663forall( otype T ) T * memset( T * ptr );                                // remove when default value available
4664\end{lstlisting}
4665\
4666
4667\subsection{ato / strto}
4668
4669\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4670int ato( const char * ptr );§\indexc{ato}§
4671unsigned int ato( const char * ptr );
4672long int ato( const char * ptr );
4673unsigned long int ato( const char * ptr );
4674long long int ato( const char * ptr );
4675unsigned long long int ato( const char * ptr );
4676float ato( const char * ptr );
4677double ato( const char * ptr );
4678long double ato( const char * ptr );
4679float _Complex ato( const char * ptr );
4680double _Complex ato( const char * ptr );
4681long double _Complex ato( const char * ptr );
4682
4683int strto( const char * sptr, char ** eptr, int base );
4684unsigned int strto( const char * sptr, char ** eptr, int base );
4685long int strto( const char * sptr, char ** eptr, int base );
4686unsigned long int strto( const char * sptr, char ** eptr, int base );
4687long long int strto( const char * sptr, char ** eptr, int base );
4688unsigned long long int strto( const char * sptr, char ** eptr, int base );
4689float strto( const char * sptr, char ** eptr );
4690double strto( const char * sptr, char ** eptr );
4691long double strto( const char * sptr, char ** eptr );
4692float _Complex strto( const char * sptr, char ** eptr );
4693double _Complex strto( const char * sptr, char ** eptr );
4694long double _Complex strto( const char * sptr, char ** eptr );
4695\end{lstlisting}
4696\
4697
4698
4699\subsection{bsearch / qsort}
4700
4701\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4702forall( otype T | { int ?<?( T, T ); } )
4703T * bsearch( const T key, const T * arr, size_t dimension );§\indexc{bsearch}§
4704
4705forall( otype T | { int ?<?( T, T ); } )
4706void qsort( const T * arr, size_t dimension );§\indexc{qsort}§
4707\end{lstlisting}
4708\
4709
4710
4711\subsection{abs}
4712
4713\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4714char abs( char );§\indexc{abs}§
4715int abs( int );
4716long int abs( long int );
4717long long int abs( long long int );
4718float abs( float );
4719double abs( double );
4720long double abs( long double );
4721float abs( float _Complex );
4722double abs( double _Complex );
4723long double abs( long double _Complex );
4724\end{lstlisting}
4725\
4726
4727
4728\subsection{random}
4729
4730\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4731void rand48seed( long int s );§\indexc{rand48seed}§
4732char rand48();§\indexc{rand48}§
4733int rand48();
4734unsigned int rand48();
4735long int rand48();
4736unsigned long int rand48();
4737float rand48();
4738double rand48();
4739float _Complex rand48();
4740double _Complex rand48();
4741long double _Complex rand48();
4742\end{lstlisting}
4743\
4744
4745
4746\subsection{min / max / swap}
4747
4748\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4749forall( otype T | { int ?<?( T, T ); } )
4750T min( const T t1, const T t2 );§\indexc{min}§
4751
4752forall( otype T | { int ?>?( T, T ); } )
4753T max( const T t1, const T t2 );§\indexc{max}§
4754
4755forall( otype T )
4756void swap( T * t1, T * t2 );§\indexc{swap}§
4757\end{lstlisting}
4758\
4759
4760
4761\section{Math Library}
4762\label{s:Math Library}
4763
4764The goal of the \CFA math-library is to wrap many of the existing C math library-routines that are explicitly polymorphic into implicitly polymorphic versions.
4765
4766
4767\subsection{General}
4768
4769\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4770float fabs( float );§\indexc{fabs}§
4771double fabs( double );
4772long double fabs( long double );
4773float cabs( float _Complex );
4774double cabs( double _Complex );
4775long double cabs( long double _Complex );
4776
4777float ?%?( float, float );§\indexc{fmod}§
4778float fmod( float, float );
4779double ?%?( double, double );
4780double fmod( double, double );
4781long double ?%?( long double, long double );
4782long double fmod( long double, long double );
4783
4784float remainder( float, float );§\indexc{remainder}§
4785double remainder( double, double );
4786long double remainder( long double, long double );
4787
4788[ int, float ] remquo( float, float );§\indexc{remquo}§
4789float remquo( float, float, int * );
4790[ int, double ] remquo( double, double );
4791double remquo( double, double, int * );
4792[ int, long double ] remquo( long double, long double );
4793long double remquo( long double, long double, int * );
4794
4795[ int, float ] div( float, float );                                             // alternative name for remquo
4796float div( float, float, int * );§\indexc{div}§
4797[ int, double ] div( double, double );
4798double div( double, double, int * );
4799[ int, long double ] div( long double, long double );
4800long double div( long double, long double, int * );
4801
4802float fma( float, float, float );§\indexc{fma}§
4803double fma( double, double, double );
4804long double fma( long double, long double, long double );
4805
4806float fdim( float, float );§\indexc{fdim}§
4807double fdim( double, double );
4808long double fdim( long double, long double );
4809
4810float nan( const char * );§\indexc{nan}§
4811double nan( const char * );
4812long double nan( const char * );
4813\end{lstlisting}
4814\
4815
4816
4817\subsection{Exponential}
4818
4819\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4820float exp( float );§\indexc{exp}§
4821double exp( double );
4822long double exp( long double );
4823float _Complex exp( float _Complex );
4824double _Complex exp( double _Complex );
4825long double _Complex exp( long double _Complex );
4826
4827float exp2( float );§\indexc{exp2}§
4828double exp2( double );
4829long double exp2( long double );
4830float _Complex exp2( float _Complex );
4831double _Complex exp2( double _Complex );
4832long double _Complex exp2( long double _Complex );
4833
4834float expm1( float );§\indexc{expm1}§
4835double expm1( double );
4836long double expm1( long double );
4837
4838float log( float );§\indexc{log}§
4839double log( double );
4840long double log( long double );
4841float _Complex log( float _Complex );
4842double _Complex log( double _Complex );
4843long double _Complex log( long double _Complex );
4844
4845float log2( float );§\indexc{log2}§
4846double log2( double );
4847long double log2( long double );
4848float _Complex log2( float _Complex );
4849double _Complex log2( double _Complex );
4850long double _Complex log2( long double _Complex );
4851
4852float log10( float );§\indexc{log10}§
4853double log10( double );
4854long double log10( long double );
4855float _Complex log10( float _Complex );
4856double _Complex log10( double _Complex );
4857long double _Complex log10( long double _Complex );
4858
4859float log1p( float );§\indexc{log1p}§
4860double log1p( double );
4861long double log1p( long double );
4862
4863int ilogb( float );§\indexc{ilogb}§
4864int ilogb( double );
4865int ilogb( long double );
4866
4867float logb( float );§\indexc{logb}§
4868double logb( double );
4869long double logb( long double );
4870\end{lstlisting}
4871\
4872
4873
4874\subsection{Power}
4875
4876\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4877float sqrt( float );§\indexc{sqrt}§
4878double sqrt( double );
4879long double sqrt( long double );
4880float _Complex sqrt( float _Complex );
4881double _Complex sqrt( double _Complex );
4882long double _Complex sqrt( long double _Complex );
4883
4884float cbrt( float );§\indexc{cbrt}§
4885double cbrt( double );
4886long double cbrt( long double );
4887
4888float hypot( float, float );§\indexc{hypot}§
4889double hypot( double, double );
4890long double hypot( long double, long double );
4891
4892float pow( float, float );§\indexc{pow}§
4893double pow( double, double );
4894long double pow( long double, long double );
4895float _Complex pow( float _Complex, float _Complex );
4896double _Complex pow( double _Complex, double _Complex );
4897long double _Complex pow( long double _Complex, long double _Complex );
4898\end{lstlisting}
4899\
4900
4901
4902\subsection{Trigonometric}
4903
4904\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4905float sin( float );§\indexc{sin}§
4906double sin( double );
4907long double sin( long double );
4908float _Complex sin( float _Complex );
4909double _Complex sin( double _Complex );
4910long double _Complex sin( long double _Complex );
4911
4912float cos( float );§\indexc{cos}§
4913double cos( double );
4914long double cos( long double );
4915float _Complex cos( float _Complex );
4916double _Complex cos( double _Complex );
4917long double _Complex cos( long double _Complex );
4918
4919float tan( float );§\indexc{tan}§
4920double tan( double );
4921long double tan( long double );
4922float _Complex tan( float _Complex );
4923double _Complex tan( double _Complex );
4924long double _Complex tan( long double _Complex );
4925
4926float asin( float );§\indexc{asin}§
4927double asin( double );
4928long double asin( long double );
4929float _Complex asin( float _Complex );
4930double _Complex asin( double _Complex );
4931long double _Complex asin( long double _Complex );
4932
4933float acos( float );§\indexc{acos}§
4934double acos( double );
4935long double acos( long double );
4936float _Complex acos( float _Complex );
4937double _Complex acos( double _Complex );
4938long double _Complex acos( long double _Complex );
4939
4940float atan( float );§\indexc{atan}§
4941double atan( double );
4942long double atan( long double );
4943float _Complex atan( float _Complex );
4944double _Complex atan( double _Complex );
4945long double _Complex atan( long double _Complex );
4946
4947float atan2( float, float );§\indexc{atan2}§
4948double atan2( double, double );
4949long double atan2( long double, long double );
4950
4951float atan( float, float );                                                             // alternative name for atan2
4952double atan( double, double );§\indexc{atan}§
4953long double atan( long double, long double );
4954\end{lstlisting}
4955\
4956
4957
4958\subsection{Hyperbolic}
4959
4960\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4961float sinh( float );§\indexc{sinh}§
4962double sinh( double );
4963long double sinh( long double );
4964float _Complex sinh( float _Complex );
4965double _Complex sinh( double _Complex );
4966long double _Complex sinh( long double _Complex );
4967
4968float cosh( float );§\indexc{cosh}§
4969double cosh( double );
4970long double cosh( long double );
4971float _Complex cosh( float _Complex );
4972double _Complex cosh( double _Complex );
4973long double _Complex cosh( long double _Complex );
4974
4975float tanh( float );§\indexc{tanh}§
4976double tanh( double );
4977long double tanh( long double );
4978float _Complex tanh( float _Complex );
4979double _Complex tanh( double _Complex );
4980long double _Complex tanh( long double _Complex );
4981
4982float asinh( float );§\indexc{asinh}§
4983double asinh( double );
4984long double asinh( long double );
4985float _Complex asinh( float _Complex );
4986double _Complex asinh( double _Complex );
4987long double _Complex asinh( long double _Complex );
4988
4989float acosh( float );§\indexc{acosh}§
4990double acosh( double );
4991long double acosh( long double );
4992float _Complex acosh( float _Complex );
4993double _Complex acosh( double _Complex );
4994long double _Complex acosh( long double _Complex );
4995
4996float atanh( float );§\indexc{atanh}§
4997double atanh( double );
4998long double atanh( long double );
4999float _Complex atanh( float _Complex );
5000double _Complex atanh( double _Complex );
5001long double _Complex atanh( long double _Complex );
5002\end{lstlisting}
5003\
5004
5005
5006\subsection{Error / Gamma}
5007
5008\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5009float erf( float );§\indexc{erf}§
5010double erf( double );
5011long double erf( long double );
5012float _Complex erf( float _Complex );
5013double _Complex erf( double _Complex );
5014long double _Complex erf( long double _Complex );
5015
5016float erfc( float );§\indexc{erfc}§
5017double erfc( double );
5018long double erfc( long double );
5019float _Complex erfc( float _Complex );
5020double _Complex erfc( double _Complex );
5021long double _Complex erfc( long double _Complex );
5022
5023float lgamma( float );§\indexc{lgamma}§
5024double lgamma( double );
5025long double lgamma( long double );
5026float lgamma( float, int * );
5027double lgamma( double, int * );
5028long double lgamma( long double, int * );
5029
5030float tgamma( float );§\indexc{tgamma}§
5031double tgamma( double );
5032long double tgamma( long double );
5033\end{lstlisting}
5034\
5035
5036
5037\subsection{Nearest Integer}
5038
5039\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5040float floor( float );§\indexc{floor}§
5041double floor( double );
5042long double floor( long double );
5043
5044float ceil( float );§\indexc{ceil}§
5045double ceil( double );
5046long double ceil( long double );
5047
5048float trunc( float );§\indexc{trunc}§
5049double trunc( double );
5050long double trunc( long double );
5051
5052float rint( float );§\indexc{rint}§
5053long double rint( long double );
5054long int rint( float );
5055long int rint( double );
5056long int rint( long double );
5057long long int rint( float );
5058long long int rint( double );
5059long long int rint( long double );
5060
5061long int lrint( float );§\indexc{lrint}§
5062long int lrint( double );
5063long int lrint( long double );
5064long long int llrint( float );
5065long long int llrint( double );
5066long long int llrint( long double );
5067
5068float nearbyint( float );§\indexc{nearbyint}§
5069double nearbyint( double );
5070long double nearbyint( long double );
5071
5072float round( float );§\indexc{round}§
5073long double round( long double );
5074long int round( float );
5075long int round( double );
5076long int round( long double );
5077long long int round( float );
5078long long int round( double );
5079long long int round( long double );
5080
5081long int lround( float );§\indexc{lround}§
5082long int lround( double );
5083long int lround( long double );
5084long long int llround( float );
5085long long int llround( double );
5086long long int llround( long double );
5087\end{lstlisting}
5088\
5089
5090
5091\subsection{Manipulation}
5092
5093\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5094float copysign( float, float );§\indexc{copysign}§
5095double copysign( double, double );
5096long double copysign( long double, long double );
5097
5098float frexp( float, int * );§\indexc{frexp}§
5099double frexp( double, int * );
5100long double frexp( long double, int * );
5101
5102float ldexp( float, int );§\indexc{ldexp}§
5103double ldexp( double, int );
5104long double ldexp( long double, int );
5105
5106[ float, float ] modf( float );§\indexc{modf}§
5107float modf( float, float * );
5108[ double, double ] modf( double );
5109double modf( double, double * );
5110[ long double, long double ] modf( long double );
5111long double modf( long double, long double * );
5112
5113float nextafter( float, float );§\indexc{nextafter}§
5114double nextafter( double, double );
5115long double nextafter( long double, long double );
5116
5117float nexttoward( float, long double );§\indexc{nexttoward}§
5118double nexttoward( double, long double );
5119long double nexttoward( long double, long double );
5120
5121float scalbn( float, int );§\indexc{scalbn}§
5122double scalbn( double, int );
5123long double scalbn( long double, int );
5124
5125float scalbln( float, long int );§\indexc{scalbln}§
5126double scalbln( double, long int );
5127long double scalbln( long double, long int );
5128\end{lstlisting}
5129\
5130
5131
5132\section{Rational Numbers}
5133\label{s:RationalNumbers}
5134
5135Rational numbers are numbers written as a ratio, i.e., as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers.
5136When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible.
5137
5138\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5139// implementation
5140struct Rational {§\indexc{Rational}§
5141        long int numerator, denominator;                                        // invariant: denominator > 0
5142}; // Rational
5143
5144// constants
5145extern struct Rational 0;
5146extern struct Rational 1;
5147
5148// constructors
5149Rational rational();
5150Rational rational( long int n );
5151Rational rational( long int n, long int d );
5152
5153// getter/setter for numerator/denominator
5154long int numerator( Rational r );
5155long int numerator( Rational r, long int n );
5156long int denominator( Rational r );
5157long int denominator( Rational r, long int d );
5158
5159// comparison
5160int ?==?( Rational l, Rational r );
5161int ?!=?( Rational l, Rational r );
5162int ?<?( Rational l, Rational r );
5163int ?<=?( Rational l, Rational r );
5164int ?>?( Rational l, Rational r );
5165int ?>=?( Rational l, Rational r );
5166
5167// arithmetic
5168Rational -?( Rational r );
5169Rational ?+?( Rational l, Rational r );
5170Rational ?-?( Rational l, Rational r );
5171Rational ?*?( Rational l, Rational r );
5172Rational ?/?( Rational l, Rational r );
5173
5174// conversion
5175double widen( Rational r );
5176Rational narrow( double f, long int md );
5177
5178// I/O
5179forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * );
5180forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational );
5181\end{lstlisting}
5182
5183
5184\bibliographystyle{plain}
5185\bibliography{cfa}
5186
5187
5188\addcontentsline{toc}{section}{\indexname} % add index name to table of contents
5189\begin{theindex}
5190Italic page numbers give the location of the main entry for the referenced term.
5191Plain page numbers denote uses of the indexed term.
5192Entries for grammar non-terminals are italicized.
5193A typewriter font is used for grammar terminals and program identifiers.
5194\indexspace
5195\input{user.ind}
5196\end{theindex}
5197
5198
5199\end{document}
5200
5201% Local Variables: %
5202% tab-width: 4 %
5203% fill-column: 100 %
5204% compile-command: "make" %
5205% End: %
Note: See TracBrowser for help on using the repository browser.