source: doc/user/user.tex @ 5c6afcd

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 5c6afcd was ec129c4, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

add additional #defines for CFA version numbers

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