source: doc/user/user.tex @ bf1a2bf

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

user manual updates, discussion on named arguments

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