source: doc/user/user.tex @ 5479e63

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

documentation for switch/choose statement

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