source: doc/user/user.tex @ 7b2c0a99

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

struggling with LaTeX macros (it's winning)

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