source: doc/user/user.tex @ 79f64f1

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

fix merge problem

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