source: doc/user/user.tex @ a0ad7dc

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 a0ad7dc was 2264c11, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

create cfa lstnewenvironment

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