source: doc/user/user.tex @ 9059213

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 9059213 was 9059213, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

small changes to bring me up to date

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