source: doc/user/user.tex @ 182fe1e

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

update switch documentation and LaTeX macros

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