source: doc/user/user.tex @ c45170a

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since c45170a was c45170a, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

update switch documentation and LaTeX macros

  • Property mode set to 100644
File size: 201.7 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 08:43:49 2016
14%% Update Count     : 1270
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 suggested 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.
1807Therefore, 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:
1808\begin{lstlisting}
1809®choose® ( i ) {
1810  case 1:  case 2:  case 3:
1811        ...
1812        ®// implicit end of switch (break)
1813  ®case 5:
1814        ...
1815        ®fallthru®;                                     §\C{// explicit fall through}§
1816  case 7:
1817        ...
1818        ®break®                                         §\C{// explicit end of switch}§
1819  default:
1820        j = 3;
1821}
1822\end{lstlisting}
1823Like the ©switch© statement, the ©choose© statement retains the fall-through semantics for a list of ©case© clauses;
1824the implicit ©break© is applied only at the end of the \emph{statements} following a ©case© clause.
1825The 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.
1826As well, allowing an explicit ©break© from the ©choose© is a carry over from the ©switch© statement, and expected by C programmers.
1827\item
1828\Index*{Duff's device} is eliminated from both ©switch© and ©choose© statements, and only invalidates a small amount of very questionable code.
1829Hence, 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.
1830\item
1831The 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.
1832Therefore, no change is made for this issue.
1833\item
1834Dealing 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{
1835Essentially, 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.
1836Further declarations at the same nesting level as the statement body are disallowed to ensure every transfer into the body is sound.
1837\begin{lstlisting}
1838switch ( x ) {
1839        ®int i = 0;®                            §\C{// allowed only at start}§
1840  case 0:
1841        ...
1842        ®int j = 0;®                            §\C{// disallowed}§
1843  case 1:
1844    {
1845                ®int k = 0;®                    §\C{// allowed at different nesting levels}§
1846                ...
1847        }
1848  ...
1849}
1850\end{lstlisting}
1851\end{enumerate}
1852
1853
1854\section{Case Clause}
1855
1856C restricts the ©case© clause of a ©switch© statement to a single value.
1857For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values.
1858Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C.
1859Therefore, the ©case© clause is extended with a list of values, as in:
1860\begin{quote2}
1861\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1862\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\
1863\begin{lstlisting}
1864switch ( i ) {
1865  ®case 1, 3, 5®:
1866        ...
1867  ®case 2, 4, 6®:
1868        ...
1869}
1870\end{lstlisting}
1871&
1872\begin{lstlisting}
1873switch ( i ) {
1874  case 1: case 3 : case 5:
1875        ...
1876  case 2: case 4 : case 6:
1877        ...
1878}
1879\end{lstlisting}
1880&
1881\begin{lstlisting}
1882
1883// odd values
1884
1885// even values
1886
1887
1888\end{lstlisting}
1889\end{tabular}
1890\end{quote2}
1891In addition, two forms of subranges are allowed to specify case values: a new \CFA form and an existing GNU C form.\footnote{
1892The GNU C form \emph{requires} spaces around the ellipse.}
1893\begin{quote2}
1894\begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}}
1895\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{GNU C}}     \\
1896\begin{lstlisting}
1897switch ( i ) {
1898  ®case 1~5:®
1899        ...
1900  ®case 10~15:®
1901        ...
1902}
1903\end{lstlisting}
1904&
1905\begin{lstlisting}
1906switch ( i )
1907  case 1 ... 5:
1908        ...
1909  case 10 ... 15:
1910        ...
1911}
1912\end{lstlisting}
1913&
1914\begin{lstlisting}
1915
1916// 1, 2, 3, 4, 5
1917
1918// 10, 11, 12, 13, 14, 15
1919
1920
1921\end{lstlisting}
1922\end{tabular}
1923\end{quote2}
1924Lists of subranges are also allowed.
1925\begin{lstlisting}
1926case ®1~5, 12~21, 35~42®:
1927\end{lstlisting}
1928
1929
1930\section{Exception Handling}
1931
1932Exception handling provides two mechanism: change of control flow from a raise to a handler, and communication from the raise to the handler.
1933\begin{lstlisting}
1934exception void h( int i );
1935exception int h( int i, double d );
1936
1937void f(...) {
1938        ... throw h( 3 );
1939        ... i = resume h( 3, 5.1 );
1940}
1941
1942try {
1943        f(...);
1944} catch h( int w ) {
1945        // reset
1946} resume h( int p, double x ) {
1947        return 17;  // recover
1948} finally {
1949}
1950\end{lstlisting}
1951So 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.
1952The 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.
1953
1954
1955\section{Types}
1956
1957\subsection{Type Definitions}
1958
1959\CFA allows users to define new types using the keyword type.
1960
1961\begin{lstlisting}
1962// SensorValue is a distinct type and represented as an int
1963type SensorValue = int;
1964\end{lstlisting}
1965
1966A 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.
1967This means that users can define distinct function overloads for the new type (see Overloading for more information).
1968For example:
1969
1970\begin{lstlisting}
1971type SensorValue = int;
1972void printValue(int v) {...}
1973void printValue(SensorValue v) {...}
1974void process(int v) {...}
1975
1976SensorValue s = ...;
1977
1978printValue(s); // calls version with SensorValue argument
1979
1980printValue((int) s); // calls version with int argument
1981
1982process(s); // implicit conversion to int
1983\end{lstlisting}
1984
1985If SensorValue was defined with a typedef, then these two print functions would not have unique signatures.
1986This can be very useful to create a distinct type that has the same representation as another type.
1987
1988The compiler will assume it can safely convert from the old type to the new type, implicitly.
1989Users may override this and define a function that must be called to convert from one type to another.
1990
1991\begin{lstlisting}
1992type SensorValue = int;
1993// ()? is the overloaded conversion operator identifier
1994// This function converts an int to a SensorValue
1995SensorValue ()?(int val) {
1996        ...
1997}
1998void process(int v) {...}
1999
2000SensorValue s = ...;
2001process(s); // implicit call to conversion operator
2002\end{lstlisting}
2003
2004In many cases, it is not desired for the compiler to do this implicit conversion.
2005To avoid that, the user can use the explicit modifier on the conversion operator.
2006Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error.
2007
2008\begin{lstlisting}
2009type SensorValue = int;
2010
2011// conversion from int to SensorValue; must be explicit
2012explicit SensorValue ()?(int val) {
2013        ...
2014}
2015
2016void process(int v) {...}
2017
2018SensorValue s = ...;
2019process(s); // implicit cast to int: compile-time error
2020process((int) s); // explicit cast to int: calls conversion func
2021\end{lstlisting}
2022
2023The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to:
2024\begin{lstlisting}
2025type SensorValue = int;
2026explicit SensorValue ()?(int);
2027void process(int v) {...}
2028
2029SensorValue s = ...;
2030process(s); // compile-time error
2031process((int) s); // type is converted, no function is called
2032\end{lstlisting}
2033
2034
2035\subsection{Structures}
2036
2037Structures in \CFA are basically the same as structures in C.
2038A structure is defined with the same syntax as in C.
2039When referring to a structure in \CFA, users may omit the struct keyword.
2040\begin{lstlisting}
2041struct Point {
2042        double x;
2043        double y;
2044};
2045
2046Point p = {0.0, 0.0};
2047\end{lstlisting}
2048
2049\CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields.
2050Composition is achieved by embedding one type into another.
2051When 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.
2052Embedding types is achieved using anonymous members.
2053For example, using Point from above:
2054\begin{lstlisting}
2055void foo(Point p);
2056
2057struct ColoredPoint {
2058        Point; // anonymous member (no identifier)
2059        int Color;
2060};
2061...
2062        ColoredPoint cp = ...;
2063        cp.x = 10.3; // x from Point is accessed directly
2064        cp.color = 0x33aaff; // color is accessed normally
2065        foo(cp); // cp can be used directly as a Point
2066\end{lstlisting}
2067
2068
2069\subsection{Constructors and Destructors}
2070
2071\CFA supports C initialization of structures, but it also adds constructors for more advanced initialization.
2072Additionally, \CFA adds destructors that are called when a variable is de-allocated (variable goes out of scope or object is deleted).
2073These functions take a reference to the structure as a parameter (see References for more information).
2074
2075\begin{figure}
2076\begin{lstlisting}
2077struct Widget {
2078        int id;
2079        float size;
2080        Parts *optionalParts;
2081};
2082
2083// ?{} is the constructor operator identifier
2084// The first argument is a reference to the type to initialize
2085// Subsequent arguments can be specified for initialization
2086
2087void ?{}(Widget &w) { // default constructor
2088        w.id = -1;
2089        w.size = 0.0;
2090        w.optionalParts = 0;
2091}
2092
2093// constructor with values (does not need to include all fields)
2094void ?{}(Widget &w, int id, float size) {
2095        w.id = id;
2096        w.size = size;
2097        w.optionalParts = 0;
2098}
2099
2100// ^? is the destructor operator identifier
2101void ^?(Widget &w) { // destructor
2102        w.id = 0;
2103        w.size = 0.0;
2104        if (w.optionalParts != 0) {
2105        // This is the only pointer to optionalParts, free it
2106        free(w.optionalParts);
2107        w.optionalParts = 0;
2108        }
2109}
2110
2111Widget baz; // reserve space only
2112Widget foo{}; // calls default constructor
2113Widget bar{23, 2.45}; // calls constructor with values
2114baz{24, 0.91}; // calls constructor with values
2115?{}(baz, 24, 0.91}; // explicit call to constructor
2116^bar; // explicit call to destructor
2117^?(bar); // explicit call to destructor
2118\end{lstlisting}
2119\caption{Constructors and Destructors}
2120\end{figure}
2121
2122
2123\begin{comment}
2124\section{References}
2125
2126
2127By introducing references in parameter types, users are given an easy way to pass a value by reference, without the need for NULL pointer checks.
2128In structures, a reference can replace a pointer to an object that should always have a valid value.
2129When a structure contains a reference, all of its constructors must initialize the reference and all instances of this structure must initialize it upon definition.
2130
2131The syntax for using references in \CFA is the same as \CC with the exception of reference initialization.
2132Use ©&© to specify a reference, and access references just like regular objects, not like pointers (use dot notation to access fields).
2133When initializing a reference, \CFA uses a different syntax which differentiates reference initialization from assignment to a reference.
2134The ©&© 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.
2135\end{comment}
2136
2137
2138\section{Overloading}
2139
2140Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name.
2141In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C.
2142This may cause identical C and \CFA programs to behave differently.
2143The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used.
2144Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users.
2145Disadvantages 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.
2146\CFA allows overloading of functions, operators, variables, and even the constants 0 and 1.
2147
2148The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads.
2149The best valid interpretations are the valid interpretations that use the fewest unsafe conversions.
2150Of these, the best are those where the functions and objects involved are the least polymorphic.
2151Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions.
2152Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions.
2153If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous.
2154For details about type inference and overload resolution, please see the \CFA Language Specification.
2155\begin{lstlisting}
2156int foo(int a, int b) {
2157        float sum = 0.0;
2158        float special = 1.0;
2159        {
2160                int sum = 0;
2161                // both the float and int versions of sum are available
2162                float special = 4.0;
2163                // this inner special hides the outer version
2164                ...
2165        }
2166        ...
2167}
2168\end{lstlisting}
2169
2170
2171\subsection{Overloaded Constant}
2172
2173The constants 0 and 1 have special meaning.
2174In \CFA, as in C, all scalar types can be incremented and
2175decremented, which is defined in terms of adding or subtracting 1.
2176The 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)©).
2177
2178In 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.
2179However, 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.
2180Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©.
2181
2182Why just 0 and 1? Why not other integers? No other integers have special status in C.
2183A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement.
2184Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed.
2185The complexity of such a feature does not seem worth the gain.
2186
2187For example, to define the constants for a complex type, the programmer would define the following:
2188
2189\begin{lstlisting}
2190struct Complex {
2191        double real;
2192        double imaginary;
2193}
2194
2195const Complex 0 = {0, 0};
2196const Complex 1 = {1, 0};
2197...
2198
2199        Complex a = 0;
2200...
2201
2202        a++;
2203...
2204        if (a) { // same as if (a == 0)
2205...
2206}
2207\end{lstlisting}
2208
2209
2210\subsection{Variable Overloading}
2211
2212The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types.
2213Allowing 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.
2214For example, a developer may want to do the following:
2215\begin{lstlisting}
2216int pi = 3;
2217float pi = 3.14;
2218char pi = .p.;
2219\end{lstlisting}
2220
2221
2222\subsection{Function Overloading}
2223
2224Overloaded 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).
2225
2226The examples below give some basic intuition about how the resolution works.
2227\begin{lstlisting}
2228// Choose the one with less conversions
2229int doSomething(int value) {...} // option 1
2230int doSomething(short value) {...} // option 2
2231
2232int a, b = 4;
2233short c = 2;
2234
2235a = doSomething(b); // chooses option 1
2236a = doSomething(c); // chooses option 2
2237
2238// Choose the specialized version over the generic
2239
2240generic(type T)
2241T bar(T rhs, T lhs) {...} // option 3
2242float bar(float rhs, float lhs){...} // option 4
2243float a, b, c;
2244double d, e, f;
2245c = bar(a, b); // chooses option 4
2246
2247// specialization is preferred over unsafe conversions
2248
2249f = bar(d, e); // chooses option 5
2250\end{lstlisting}
2251
2252
2253\subsection{Operator Overloading}
2254
2255\CFA also allows operators to be overloaded, to simplify the use of user-defined types.
2256Overloading 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.
2257\CFA uses the following special identifiers to name overloaded operators:
2258
2259\begin{table}[hbt]
2260\hfil
2261\begin{tabular}[t]{ll}
2262%identifier & operation \\ \hline
2263©?[?]© & subscripting \impl{?[?]}\\
2264©?()© & function call \impl{?()}\\
2265©?++© & postfix increment \impl{?++}\\
2266©?--© & postfix decrement \impl{?--}\\
2267©++?© & prefix increment \impl{++?}\\
2268©--?© & prefix decrement \impl{--?}\\
2269©*?© & dereference \impl{*?}\\
2270©+?© & unary plus \impl{+?}\\
2271©-?© & arithmetic negation \impl{-?}\\
2272©~?© & bitwise negation \impl{~?}\\
2273©!?© & logical complement \impl{"!?}\\
2274©?*?© & multiplication \impl{?*?}\\
2275©?/?© & division \impl{?/?}\\
2276\end{tabular}\hfil
2277\begin{tabular}[t]{ll}
2278%identifier & operation \\ \hline
2279©?%?© & remainder \impl{?%?}\\
2280©?+?© & addition \impl{?+?}\\
2281©?-?© & subtraction \impl{?-?}\\
2282©?<<?© & left shift \impl{?<<?}\\
2283©?>>?© & right shift \impl{?>>?}\\
2284©?<?© & less than \impl{?<?}\\
2285©?<=?© & less than or equal \impl{?<=?}\\
2286©?>=?© & greater than or equal \impl{?>=?}\\
2287©?>?© & greater than \impl{?>?}\\
2288©?==?© & equality \impl{?==?}\\
2289©?!=?© & inequality \impl{?"!=?}\\
2290©?&& bitwise AND \impl{?&?}\\
2291\end{tabular}\hfil
2292\begin{tabular}[t]{ll}
2293%identifier & operation \\ \hline
2294©?^& exclusive OR \impl{?^?}\\
2295©?|?© & inclusive OR \impl{?"|?}\\
2296©?=?© & simple assignment \impl{?=?}\\
2297©?*=?© & multiplication assignment \impl{?*=?}\\
2298©?/=?© & division assignment \impl{?/=?}\\
2299©?%=?© & remainder assignment \impl{?%=?}\\
2300©?+=?© & addition assignment \impl{?+=?}\\
2301©?-=?© & subtraction assignment \impl{?-=?}\\
2302©?<<=?© & left-shift assignment \impl{?<<=?}\\
2303©?>>=?© & right-shift assignment \impl{?>>=?}\\
2304©?&=?© & bitwise AND assignment \impl{?&=?}\\
2305©?^=?© & exclusive OR assignment \impl{?^=?}\\
2306©?|=?© & inclusive OR assignment \impl{?"|=?}\\
2307\end{tabular}
2308\hfil
2309\caption{Operator Identifiers}
2310\label{opids}
2311\end{table}
2312
2313These identifiers are defined such that the question marks in the name identify the location of the operands.
2314These operands represent the parameters to the functions, and define how the operands are mapped to the function call.
2315For example, ©a + b© becomes ©?+?(a, b)©.
2316
2317In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator.
2318These operators are called using the normal C syntax.
2319
2320\begin{lstlisting}
2321type Complex = struct { // define a Complex type
2322        double real;
2323        double imag;
2324}
2325
2326// Constructor with default values
2327
2328void ?{}(Complex &c, double real = 0.0, double imag = 0.0) {
2329        c.real = real;
2330        c.imag = imag;
2331}
2332
2333Complex ?+?(Complex lhs, Complex rhs) {
2334        Complex sum;
2335        sum.real = lhs.real + rhs.real;
2336        sum.imag = lhs.imag + rhs.imag;
2337        return sum;
2338}
2339
2340String ()?(const Complex c) {
2341        // use the string conversions for the structure members
2342        return (String)c.real + . + . + (String)c.imag + .i.;
2343}
2344...
2345
2346Complex a, b, c = {1.0}; // constructor for c w/ default imag
2347...
2348c = a + b;
2349print(.sum = . + c);
2350\end{lstlisting}
2351
2352
2353\section{Auto Type-Inferencing}
2354
2355Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type.
2356\begin{quote2}
2357\begin{tabular}{@{}l@{\hspace{3em}}ll@{}}
2358\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{Indexc{gcc}} \\
2359\begin{lstlisting}
2360
2361auto j = 3.0 * 4;
2362int i;
2363auto k = i;
2364\end{lstlisting}
2365&
2366\begin{lstlisting}
2367#define expr 3.0 * i
2368typeof(expr) j = expr;
2369int i;
2370typeof(i) k = i;
2371\end{lstlisting}
2372&
2373\begin{lstlisting}
2374
2375// use type of initialization expression
2376
2377// use type of primary variable
2378\end{lstlisting}
2379\end{tabular}
2380\end{quote2}
2381The two important capabilities are:
2382\begin{itemize}
2383\item
2384preventing having to determine or write out long generic types,
2385\item
2386ensure secondary variables, related to a primary variable, always have the same type.
2387\end{itemize}
2388
2389In \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.
2390\Indexc{gcc} provides ©typeof© to declare a secondary variable from a primary variable.
2391\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.
2392Only for overloaded routines with the same return type is variable type-inferencing possible.
2393Finally, ©auto© presents the programming problem of tracking down a type when the type is actually needed.
2394For example, given
2395\begin{lstlisting}
2396auto j = ®...®
2397\end{lstlisting}
2398and the need to write a routine to compute using ©j©
2399\begin{lstlisting}
2400void rtn( ®...® parm );
2401rtn( j );
2402\end{lstlisting}
2403A programmer must work backwards to determine the type of ©j©'s initialization expression, reconstructing the possibly long generic type-name.
2404In this situation, having the type name or a short alias is very useful.
2405
2406There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type.
2407That is, when is the type of the variable more important than the type of its initialization expression.
2408For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors.
2409At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes.
2410
2411Given ©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.
2412Should a significant need arise, this feature can be revisited.
2413
2414
2415\section{Generics}
2416
2417\CFA supports parametric polymorphism to allow users to define generic functions and types.
2418Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types.
2419The type parameters can be restricted to satisfy a set of constraints.
2420This 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.
2421
2422
2423\subsection{Generic Functions}
2424
2425Generic functions in \CFA are similar to template functions in \Index*[C++]{\CC}, and will sometimes be expanded into specialized versions, just like in \CC.
2426The 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.
2427This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically).
2428Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated.
2429
2430A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this:
2431
2432\begin{lstlisting}
2433generic(type T)
2434void swap(T &a, T &b) {
2435        T tmp = a;
2436        a = b;
2437        b = a;
2438}
2439
2440int a, b;
2441swap(a, b);
2442
2443Point p1, p2;
2444swap(p1, p2);
2445\end{lstlisting}
2446
2447Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T.
2448This 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.
2449
2450
2451\subsection{Bounded Quantification}
2452
2453Some generic functions only work (or make sense) for any type that satisfies a given property.
2454For example, here is a function to pick the minimum of two values of some type.
2455\begin{lstlisting}
2456generic (type T | bool ?<?(T, T) )
2457
2458T min(T a, T b) {
2459        return a < b ? a : b;
2460}
2461\end{lstlisting}
2462
2463It 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.
2464The ordering function used here is the less than operator, <.
2465The syntax used to reference the operator is discussed in further detail in Operator Overloading.
2466In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)).
2467The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise.
2468
2469Bounds can also involve multiple types, and multiple requirements, as shown below:
2470\begin{lstlisting}
2471generic (type T, type U | { T foo(T, U); U bar(U); })
2472
2473T baz(T t, U u) {
2474        return foo(t, bar(u));
2475}
2476\end{lstlisting}
2477
2478
2479\subsection{Interfaces}
2480
2481Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type.
2482Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined.
2483Can 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.
2484The function signature doesn't say.
2485
2486Interfaces gather together a set of function signatures under a common name, which solves two problems.
2487First, an interface name can be used in type bounds instead of function signatures.
2488This avoids repetition when a bound is used in many functions.
2489Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand.
2490\begin{lstlisting}
2491generic (type T)
2492interface Orderable {
2493        bool ?<?(T, T);
2494};
2495
2496generic (type T | Orderable(T))
2497T min(T a, T b) {
2498        return a < b ? a : b;
2499}
2500\end{lstlisting}
2501
2502This definition of the interface Orderable makes the generic function min easier to read and understand.
2503Orderable can also be reused for other generic functions, max for example.
2504Interfaces can also build on top of other interfaces.
2505For example:
2506\begin{lstlisting}
2507generic (type T | Orderable(T)
2508interface FooBarable {
2509        int foo(T, T);
2510        int Bar(T, T);
2511};
2512\end{lstlisting}
2513
2514The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition.
2515A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time.
2516For 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.
2517
2518
2519\subsection{Generic Typedefs}
2520
2521Type synonyms can be defined generically using the typedef keyword together with a generic type annotation.
2522These can be used to abbreviate complicated type expressions, especially in generic code.
2523\begin{lstlisting}
2524// typedef the generic function pointers for later use
2525
2526generic(type T)
2527typedef int (*predicate)(T);
2528generic(type Captured, type T)
2529typedef void (*callback)(Captured, T);
2530
2531generic(type T)
2532void find(int length, T *array,
2533        predicate(T) p, callback(void *, T)f) {
2534        int i;
2535        for (i = 0; i < length; i++)
2536        if (p(array[i])) f(NULL, array[i]);
2537}
2538\end{lstlisting}
2539
2540
2541\subsection{Generic Types}
2542
2543Generic types are defined using the same mechanisms as those described above for generic functions.
2544This 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}.
2545For 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.
2546In C, something like this would have to be done using void pointers and unsafe casting.
2547As 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.
2548This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds.
2549
2550The syntax for defining a generic type looks very similar to that of a generic function.
2551Generic types support bounds and interfaces, using the same syntax as generic functions.
2552\begin{lstlisting}
2553generic (type T)
2554struct LinkedListElem {
2555        T elem;
2556        LinkedListElem(T) *next;
2557};
2558
2559LinkedListElem *++?(LinkedListElem **elem) {
2560        return *elem = elem->next;
2561}
2562
2563generic (type T)
2564struct LinkedList {
2565        LinkedListElem(T) *head;
2566        unsigned int size;
2567}
2568
2569generic (type T | bool ?==?(T, T))
2570bool contains(LinkedList(T) *list, T elem) {
2571        for(LinkedListElem *iter = list->head; iter != 0; ++iter) {
2572        if (iter->elem == elem) return true;
2573        }
2574        return false;
2575}
2576\end{lstlisting}
2577
2578
2579\section{Safety}
2580
2581Safety, along with productivity, is a key goal of Do.
2582This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code.
2583
2584
2585\subsection{Exceptions}
2586
2587\CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code.
2588In C, developers can use error codes and special return values to report to a caller that an error occurred in a function.
2589The major problem with error codes is that they can be easily ignored by the caller.
2590Failure 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.
2591An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state.
2592
2593Exceptions in \CFA allow a different type of control flow.
2594Throwing 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.
2595The exception is immediately re-thrown from the parent block unless it is caught as described below.
2596\CFA uses keywords similar to \Index*[C++]{\CC} for exception handling.
2597An exception is thrown using a throw statement, which accepts one argument.
2598
2599\begin{lstlisting}
2600        ...
2601
2602        throw 13;
2603
2604        ...
2605\end{lstlisting}
2606
2607An exception can be caught using a catch statement, which specifies the type of the exception it can catch.
2608A catch is specified immediately after a guarded block to signify that it can catch an exception from that block.
2609A guarded block is specified using the try keyword, followed by a block of code inside of curly braces.
2610
2611\begin{lstlisting}
2612        ...
2613
2614        try {
2615                throw 13;
2616        }
2617        catch(int e) {
2618                printf(.caught an exception: %d\n., e);
2619        }
2620\end{lstlisting}
2621
2622
2623\subsection{Memory Management}
2624
2625
2626\subsubsection{Manual Memory Management}
2627
2628Using malloc and free to dynamically allocate memory exposes several potential, and common, errors.
2629First, malloc breaks type safety because it returns a pointer to void.
2630There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated.
2631This problem is solved with a type-safe malloc.
2632Do.s type-safe malloc does not take any arguments for size.
2633Instead, it infers the type based on the return value, and then allocates space for the inferred type.
2634
2635\begin{lstlisting}
2636float *f = malloc(); // allocates the size of a float
2637
2638struct S {
2639        int i, j, k;
2640};
2641
2642struct S *s = malloc(); // allocates the size of a struct S
2643\end{lstlisting}
2644
2645In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function.
2646For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type.
2647
2648\begin{lstlisting}
2649type Complex = struct {
2650        float real;
2651        float imag;
2652};
2653
2654// default constructor
2655
2656void ?{}(Complex &c) {
2657        c.real = 0.0;
2658        c.imag = 0.0;
2659}
2660
2661
2662
2663// 2 parameter constructor
2664
2665void ?{}(Complex &c, float real, float imag) {
2666        c.real = real;
2667        c.imag = imag;
2668}
2669
2670
2671int main() {
2672        Complex c1; // No constructor is called
2673        Complex c2{}; // Default constructor called
2674        Complex c3{1.0, -1.0}; // 2 parameter constructor is called
2675
2676        Complex *p1 = malloc(); // allocate
2677        Complex *p2 = new(); // allocate + default constructor
2678        Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor
2679}
2680
2681\end{lstlisting}
2682
2683
2684\subsubsection{Automatic Memory Management}
2685
2686\CFA may also support automatic memory management to further improve safety.
2687If 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.
2688This feature requires further investigation.
2689\CFA will not have a garbage collector, but might use some kind of region-based memory management.
2690
2691
2692\subsection{Unsafe C Constructs}
2693
2694C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming.
2695Some of these practices however are often error-prone and difficult to read and maintain.
2696Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code.
2697If 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.
2698This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway..
2699
2700The 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.
2701Once the full set is decided, the rules will be listed here.
2702
2703
2704\section{Syntactic Anomalies}
2705
2706The number 0 and 1 are treated specially in \CFA, and can be redefined as variables.
2707One syntactic anomaly is when a field in an structure is names 0 or 1:
2708\begin{lstlisting}
2709struct S {
2710        int 0, 1;
2711} s;
2712\end{lstlisting}
2713The problem occurs in accessing these fields using the selection operation ``©.©'':
2714\begin{lstlisting}
2715s.0 = 0;        // ambiguity with floating constant .0
2716s.1 = 1;        // ambiguity with floating constant .1
2717\end{lstlisting}
2718To make this work, a space is required after the field selection:
2719\begin{lstlisting}
2720®s.§\textvisiblespace§0® = 0;
2721®s.§\textvisiblespace§1® = 1;
2722\end{lstlisting}
2723While this syntax is awkward, it is unlikely many programmers will name fields of a structure 0 or 1.
2724Like 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.
2725
2726There are several ambiguous cases with operator identifiers, \eg ©int *?*?()©, where the string ©*?*?© can be lexed as ©*©/©?*?© or ©*?©/©*?©.
2727Since 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.
2728Even with this special hack, there are 5 general cases that cannot be handled.
2729The first case is for the function-call identifier ©?()©:
2730\begin{lstlisting}
2731int *§\textvisiblespace§?()();  // declaration: space required after '*'
2732\textvisiblespace§?()();              // expression: space required after '*'
2733\end{lstlisting}
2734Without the space, the string ©*?()© is ambiguous without N character look ahead;
2735it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument/parameter list.
2736
2737The 4 remaining cases occur in expressions:
2738\begin{lstlisting}
2739i++§\textvisiblespace§?i:0;             // space required before '?'
2740i--§\textvisiblespace§?i:0;             // space required before '?'
2741\textvisiblespace§?++i:0;             // space required after '?'
2742\textvisiblespace§?--i:0;             // space required after '?'
2743\end{lstlisting}
2744In the first two cases, the string ©i++?© is ambiguous, where this string can be lexed as ©i© / ©++?© or ©i++© / ©?©;
2745it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument list.
2746In the second two cases, the string ©?++x© is ambiguous, where this string can be lexed as ©?++© / ©x© or ©?© / y©++x©;
2747it requires scanning ahead to determine if there is a ©'('©, which is the start of an argument list.
2748
2749
2750\section{Concurrency}
2751
2752Today's processors for nearly all use cases, ranging from embedded systems to large cloud computing servers, are composed of multiple cores, often heterogeneous.
2753As machines grow in complexity, it becomes more difficult for a program to make the most use of the hardware available.
2754\CFA includes built-in concurrency features to enable high performance and improve programmer productivity on these multi-/many-core machines.
2755
2756Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads.
2757The model integrates concurrency features into the language by making the structure type the core unit of concurrency.
2758All communication occurs through method calls, where data is sent via method arguments, and received via the return value.
2759This enables a very familiar interface to all programmers, even those with no parallel programming experience.
2760It also allows the compiler to do static type checking of all communication, a very important safety feature.
2761This controlled communication with type safety has some similarities with channels in \Index*{Go}, and can actually implement
2762channels exactly, as well as create additional communication patterns that channels cannot.
2763Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads.
2764
2765Three new keywords are added to support these features:
2766
2767monitor creates a structure with implicit locking when accessing fields
2768
2769mutex implies use of a monitor requiring the implicit locking
2770
2771task creates a type with implicit locking, separate stack, and a thread
2772
2773
2774\subsection{Monitors}
2775
2776A monitor is a structure in \CFA which includes implicit locking of its fields.
2777Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion.
2778An example of the definition of a monitor is shown here:
2779\begin{lstlisting}
2780type Account = monitor {
2781        const unsigned long number; // account number
2782        float balance; // account balance
2783};
2784\end{lstlisting}
2785
2786Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor;
2787it is always passed by reference.
2788Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter.
2789When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body.
2790This means that a function requiring mutual exclusion could block if the lock is already held by another thread.
2791Blocking 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.
2792If multiple mutex parameters are specified, they will be locked in parameter order (\ie first parameter is locked first) and unlocked in the
2793reverse order.
2794\begin{lstlisting}
2795// This function accesses a constant field, it does not require
2796// mutual exclusion
2797
2798export unsigned long getAccountNumber(Account &a) {
2799        return a.number;
2800}
2801
2802// This function accesses and modifies a shared field; it
2803// requires mutual exclusion
2804
2805export float withdrawal(mutex Account &a, float amount) {
2806        a.balance -= amount;
2807        return a.balance;
2808}
2809\end{lstlisting}
2810
2811Often, one function using a monitor will call another function using that same monitor.
2812If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function.
2813This 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.
2814It will still be unlocked the same number of times.
2815An example of this situation is shown below:
2816
2817\begin{lstlisting}
2818// deleting a job from a worker requires mutual exclusion
2819
2820void deleteJob(mutex Worker &w, Job &j) {
2821        ...
2822}
2823
2824// transferring requires mutual exclusion and calls deleteJob
2825
2826void transferJob(mutex Worker &from, Worker &to) {
2827        ...
2828        deleteJob(j);
2829        ...
2830}
2831\end{lstlisting}
2832
2833
2834\subsection{Tasks}
2835
2836\CFA also provides a simple mechanism for creating and utilizing user level threads.
2837A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control.
2838Similar to a monitor, a task is defined like a structure:
2839\begin{lstlisting}
2840type Adder = task {
2841        int *row;
2842        int size;
2843        int &subtotal;
2844}
2845\end{lstlisting}
2846
2847A task may define a constructor, which will be called upon allocation and run on the caller.s thread.
2848A 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).
2849After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method.
2850All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error.
2851Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads.
2852(Note that this example is designed to display the syntax and functionality, not the best method to solve this problem)
2853\begin{lstlisting}
2854void ?{}(Adder &a, int r[], int s, int &st) { // constructor
2855        a.row = r;
2856        a.size = s;
2857        a.subtotal = st;
2858}
2859
2860// implicitly spawn thread and begin execution here
2861
2862void ?()(Adder &a) {
2863        int c;
2864        subtotal = 0;
2865        for (c=0; c<a.size; ++c) {
2866        subtotal += row[c];
2867        }
2868}
2869
2870int main() {
2871        const int rows = 100, cols = 1000000;
2872        int matrix[rows][cols];
2873        int subtotals[rows];
2874        int total = 0;
2875        int r;
2876
2877        { // create a new scope here for our adders
2878        Adder adders[rows];
2879        // read in the matrix
2880        ...
2881        for (r=0; r<rows; ++r) {
2882        // tasks are initialized on this thread
2883        Adders[r] = {matrix[r], cols, subtotals[r]};
2884        Adders[r](); // spawn thread and begin execution
2885        }
2886        } // adders go out of scope; block here until they all finish
2887        total += subtotals[r];
2888        printf(.total is %d\n., total);
2889}
2890\end{lstlisting}
2891
2892
2893\subsection{Cooperative Scheduling}
2894
2895Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points.
2896In Listing 31, there are no yield points, so each task runs to completion with no interruptions.
2897Places 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.
2898This 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.
2899For example, the code below defines a monitor that maintains a generic list.
2900When 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.
2901Similarly, 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.
2902
2903\begin{lstlisting}
2904// type T is used as a generic type for all definitions inside
2905// the curly brackets
2906
2907generic(type T) {
2908        type Channel = monitor {
2909        List(T) list; // list is a simple generic list type
2910        };
2911
2912        T pop(mutex &Channel(T) ch) {
2913        if (ch.list.empty()) {
2914        // yield until push is called for this channel
2915        yield(push);
2916        }
2917        return ch.list.pop();
2918        }
2919
2920        void push(mutex &Channel(T)ch, T val) {
2921        if (ch.list.full()) {
2922        // yield until pop is called for this channel
2923        yield(pop);
2924        }
2925        ch.list.push(val);
2926        }
2927}
2928\end{lstlisting}
2929
2930A task can also yield indefinitely by calling yield with no arguments.
2931This will tell the scheduler to yield this task until it is resumed by some other task.
2932A task can resume another task by using its functional call operator.
2933The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods.
2934
2935\begin{lstlisting}
2936type Ping = task {
2937        Pong *partner;
2938};
2939
2940void ?{}(Ping &p, Pong *partner = 0) {
2941        p.partner = partner;
2942}
2943
2944void ?()(Ping &p) {
2945        for(;;) { // loop forever
2946        printf(.ping\n.);
2947        partner(); // resumes the partner task
2948        yield(); // yields this task
2949        }
2950}
2951
2952type Pong = task {
2953        Ping *partner;
2954};
2955
2956void ?{}(Pong &p, Ping *partner = 0) {
2957        p.partner = partner;
2958}
2959
2960void ?()(Pong &p) {
2961        for(;;) { // loop forever
2962        yield(); // yields this task
2963        printf(.pong/n.);
2964        partner(); // resumes the partner task
2965        }
2966}
2967
2968void main() {
2969        Ping ping; // allocate ping
2970        Pong pong{ping}; // allocate, initialize, and start pong
2971        Ping{pong}; // initialize and start ping
2972}
2973\end{lstlisting}
2974
2975The same functionality can be accomplished by providing functions to be called by the partner task.
2976\begin{lstlisting}
2977type Pingpong = task {
2978        String msg;
2979        Pingpong *partner;
2980};
2981
2982void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) {
2983        p.msg = msg;
2984        p.partner = partner;
2985}
2986
2987void ?()(Pingpong &p) {
2988        for(;;) {
2989        yield(go);
2990        }
2991}
2992
2993void go(Pingpong &p) {
2994        print(.%(p.msg)\n.);
2995        go(p.partner);
2996}
2997
2998void main() {
2999        Pingpong ping = {.ping.};
3000        Pingpong pong = {.pong., ping};
3001        ping.partner = pong;
3002        go(ping);
3003}
3004\end{lstlisting}
3005
3006
3007\section{Modules and Packages }
3008
3009\begin{comment}
3010High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed.
3011\CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time.
3012
3013There are two levels of encapsulation in \CFA, module and package.
3014A 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}.
3015A module forms a namespace to limit the visibility and prevent naming conflicts of variables.
3016Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed.
3017
3018A package is a physical grouping of one or more modules that is used for code distribution and version management.
3019Package is also the level of granularity at which dependences are managed.
3020A package is similar to the Crate in \Index*{Rust}.
3021
3022
3023\subsection{No Declarations, No Header Files}
3024
3025In 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.
3026Header files and a preprocessor are normally used to avoid repeating code.
3027Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work.
3028Instead of following this model, the \CFA tools can extract all of the same information from the code automatically.
3029This 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.
3030In 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.
3031This 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.
3032
3033In \CFA, multiple definitions are not necessary.
3034Within a module, all of the module's global definitions are visible throughout the module.
3035For example, the following code compiles, even though ©isOdd© was not declared before being called:
3036\begin{lstlisting}
3037bool isEven(unsigned int x) {
3038        if (x == 0) return true;
3039        else return !isOdd(x);
3040}
3041
3042bool isOdd(unsigned int x) {
3043        if (x == 1) return true;
3044        else return !isEven(x - 2);
3045}
3046\end{lstlisting}
3047
3048Header files in C are used to expose the declarations from a library, so that they can be used externally.
3049With \CFA, this functionality is replaced with module exports, discussed below.
3050When 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.
3051
3052In 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).
3053
3054
3055\subsection{Modules}
3056
3057A 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.
3058These modules can then be easily shared and reused in multiple projects.
3059As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces.
3060
3061\CFA adds the following keywords to express the module systems: module, export, import, as.
3062
3063
3064\subsubsection{Module Declaration}
3065
3066The syntax to declare a module is module moduleName;.
3067
3068The module declaration must be at the beginning of a file, and each file can only belong to one module.
3069If there is no module declaration at the beginning of a file, the file belongs to the global module.
3070A module can span several files.
3071By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation.
3072
3073The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship.
3074For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container.
3075
3076Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface.
3077A method, a global variable or a type can be declared as a module interface.
3078Types defined in a module and referenced by an exported function or a variable must be exported, too.
3079
3080The following code is a simple module declaration example.
3081\begin{lstlisting}
3082module M;
3083
3084//visible outside module M
3085
3086export int f(int i) { return i + 1; }
3087export double aCounter;
3088
3089//not visible outside module M
3090
3091int g(int i) { return i - 1; }
3092
3093double bCounter;
3094\end{lstlisting}
3095
3096export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module.
3097
3098
3099\subsubsection{Module Import}
3100
3101The syntax to import a module is import moduleName; or import moduleName as anotherName;.
3102One package cannot be imported with both of the two types of syntax in one file.
3103A package imported in one file will only be visible in this file.
3104For example, two files, A and B belong to the same module.
3105If file A imports another module, M, the exported names in M are not visible in file B.
3106
3107All of the exported names are visible in the file that imports the module.
3108The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo).
3109If 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(...);).
3110The 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.
3111Conflicts in namespaces will be reported by the compiler.
3112The second method can be used to solve conflicting name problems.
3113The following code snippets show the two situations.
3114
3115\begin{lstlisting}
3116module util/counter;
3117export int f(int i) { return i+1; }
3118
3119import util/counter;
3120
3121int main() {
3122        return counter.f(200); // f() from the package counter
3123}
3124
3125import util/counter as ct;
3126int main() {
3127        return ct.f(200); // f() from the package counter
3128}
3129\end{lstlisting}
3130
3131
3132Additionally, 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.
3133
3134\begin{lstlisting}
3135module M1;
3136export int f(int i) { return i+1;} // visible outside
3137
3138int g(int i) { return i-1;} // not visible outside
3139
3140module M2;
3141int f(int i) { return i * 2; } // not visible outside
3142export int g(int g) { return i / 2; } // visible outside
3143
3144import M1 as .;
3145
3146import M2 as .;
3147
3148
3149int main() {
3150        return f(3) + g(4); //f() from M1 and g() from M2;
3151}
3152\end{lstlisting}
3153
3154
3155\subsubsection{Sub-Module and Module Aggregation}
3156
3157Several modules can be organized in a parent module and sub-modules relationship.
3158The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship.
3159For example, std/vector and std/io are sub-modules of module std.
3160The 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
3161not implicitly exported in the parent module.
3162
3163Aggregation is a mechanism to support components and simplified importing.
3164The mechanism is not based on naming but based on manual declaration.
3165For example, the following is the aggregated sequence module.
3166The export {...} is syntactic sugar for many lines of export module aModule;.
3167If an aggregated module is imported, all the included modules in the aggregation are imported.
3168
3169\begin{lstlisting}
3170module std/sequence;
3171
3172export {
3173        module std/vector;
3174        module std/list;
3175        module std/array;
3176        module std/deque;
3177        module std/forward_list;
3178        module std/queue;
3179        module std/stack;
3180};
3181\end{lstlisting}
3182
3183After importing the aggregated module, each individual name is still contained in the original name space.
3184For 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.
3185
3186
3187\subsubsection{Import from Repository}
3188
3189When 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).
3190The tools also support retrieving modules of a package from external repositories.
3191See Listing 40: Package directory structure
3192
3193
3194\subsubsection{Package Import}
3195
3196Because 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.
3197In 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;
3198or 2) Adding the package dependence into the current project's Do.prj.
3199More details about locating a module in a package are explained in the next section.
3200
3201
3202\subsubsection{Package Versioning}
3203
3204A package must have a version number.
3205The version number is a string.
3206For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3207By convention, a package is stored in a directory named packageName-packageVersion.
3208For example, the util package with version 1.1 is stored in a directory named util-1.1.
3209
3210The project description file can optionally specify the version of the package used in the current project.
3211If 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.
3212The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3213
3214
3215\subsection{Module and Package Organization}
3216
3217\CFA has two level of encapsulations, module and package.
3218This section explains the object model of modules, packages and other language concepts.
3219It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3220
3221
3222\subsubsection{Object Model}
3223
3224There are several concepts in Do.
3225\begin{itemize}
3226\item
3227File: a \CFA source file
3228\item
3229Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3230\item
3231Package: a container to organize modules for distribution; It has attributes like name, author,
3232version, dependences, etc.
3233\item
3234Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3235\end{itemize}
3236
3237The following rules summarize the object model of all the above concepts:
3238\begin{itemize}
3239\item
3240A module contains one or more files
3241\begin{itemize}
3242\item
3243One file can only belong to one module
3244\item
3245A module has its name and interfaces exported
3246\item
3247A file without a module declaration at the beginning belongs to the global module
3248\item
3249\end{itemize}
3250
3251\item
3252A package contains one or more modules
3253\begin{itemize}
3254\item
3255A package has additional meta info described in Do.prj file
3256\item
3257A package may be dependent on other packages.
3258\end{itemize}
3259
3260\item
3261A project contains one or more modules in its source code
3262\begin{itemize}
3263\item
3264A project has additional meta info described in Do.prj file
3265\item
3266A project may be dependent on other packages
3267\item
3268A project can be transformed into a package for distribution
3269\item
3270A project can generate one or more executable binaries
3271\end{itemize}
3272\end{itemize}
3273
3274
3275\subsubsection{Module File Organization}
3276
3277The rules of this section are the conventions to organize module files in one package.
3278
3279The file location of a module in a package must match the module/submodule naming hierarchy.
3280The names separated by slash "/" must match the directory levels.
3281If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3282The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3283
3284Here is an example of a package, util.
3285\begin{lstlisting}
3286+ util
3287Do.prj #package description file
3288        heap.do #Case 1: module heap;
3289        list.do #Case 1: mdoule list;
3290        ring.do #Case 1: module ring;
3291        + string #Case 2
3292        impl1.do #module string;
3293        + std
3294        vector.do
3295        list.do
3296        + array #Case 3
3297        array1.do #module std/array;
3298        array2.do #module std/array;
3299        sequence.do #Case 4, module std/sequence;
3300        test.do #Case 5
3301\end{lstlisting}
3302
3303\begin{itemize}
3304\item
3305Case 1: Each individual file implements a module
3306\item
3307Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3308\item
3309Case 3: Put the implementation of a module under the sub-directory; There are several files to
3310implement one module
3311\item
3312Case 4: One file to express one aggregation
3313\item
3314Case 5: The file does not belong to any module; It is used for testing purpose
3315\end{itemize}
3316
3317The example only uses source code, ".do" files, to show the module file organization.
3318Other module packaging formats, like binary, must also follow the same rules.
3319
3320
3321\subsection{Module File Format}
3322
3323\CFA supports different types of module file formats.
3324
3325\begin{itemize}
3326\item
3327Pure source code format: The files should be organized following the previous section's definition.
3328\item
3329IR format (TBD): The \CFA compiler IR format, similar to the source code format
3330\item
3331Binary format, including ".a" static library or ".so" dynamic linkage library
3332\begin{itemize}
3333\item
3334The file's name must match the right level's module name defined in the previous section
3335\item
3336E.g. "util.so" includes all modules for the package util.
3337\item
3338E.g. "string.so" under the package directory to include files belonging to "module string;"
3339\end{itemize}
3340\item.
3341Archive format
3342\begin{itemize}
3343\item
3344The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3345\item
3346E.g. "util.dar" is the whole package for util package including the package direction file
3347\end{itemize}
3348\item
3349Hybrid format
3350\begin{itemize}
3351\item
3352A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3353\item
3354The only limitation is that the names of the files must match the module location names defined in previous section
3355\end{itemize}
3356\end{itemize}
3357Package and Module Locating and the \CFA Language Tooling documentation for more details.
3358
3359
3360\subsection{Packages}
3361
3362A package is synonymous with a library in other languages.
3363The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management.
3364A package is a physical grouping of one or more modules in a directory (an archive file for a directory).
3365The 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.
3366
3367
3368\subsubsection{Package Definition}
3369
3370A package is defined by putting a project description file, Do.prj, with one or more modules into a directory.
3371This project description file contains the package's meta data, including package name, author, version, dependences, etc.
3372It should be in the root of the package directory.
3373
3374The modules in the package could be either source code, or compiled binary format.
3375The location of the module files should follow the module name's path.
3376
3377Here is a simple example of the directory structure of a package, core.
3378It contains a module std and several sub-modules under std.
3379\begin{lstlisting}
3380+ core
3381        Do.prj
3382        + std
3383        + io
3384        file.do # module std/io/file;
3385        network.do #module std/io/network;
3386        + container
3387        vector.do #module std/container/vector;
3388        list.do #module std/container/list;
3389\end{lstlisting}
3390
3391
3392\subsubsection{Package Import}
3393
3394Because 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.
3395In 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.
3396More details about locating a module in a package are explained in the next section.
3397
3398
3399\subsubsection{Package Versioning}
3400
3401A package must have a version number.
3402The version number is a string.
3403For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers.
3404By convention, a package is stored in a directory named packageName-packageVersion.
3405For example, the util package with version 1.1 is stored in a directory named util-1.1.
3406
3407The project description file can optionally specify the version of the package used in the current project.
3408If 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.
3409The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds.
3410
3411
3412\subsection{Module and Package Organization}
3413
3414\CFA has two level of encapsulations, module and package.
3415This section explains the object model of modules, packages and other language concepts.
3416It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation.
3417
3418
3419\subsubsection{Object Model}
3420
3421There are several concepts in Do.
3422\begin{itemize}
3423\item
3424File: a \CFA source file
3425\item
3426Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside
3427\item
3428Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc.
3429\item
3430Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc.
3431\end{itemize}
3432
3433The following rules summarize the object model of all the above concepts:
3434\begin{itemize}
3435\item
3436A module contains one or more files
3437\begin{itemize}
3438\item
3439One file can only belong to one module
3440\item
3441A module has its name and interfaces exported
3442\item
3443A file without a module declaration at the beginning belongs to the global module
3444\end{itemize}
3445\item
3446A package contains one or more modules
3447\begin{itemize}
3448\item
3449A package has additional meta info described in Do.prj file
3450\item
3451A package may be dependent on other packages.
3452\end{itemize}
3453\item
3454A project contains one or more modules in its source code
3455\begin{itemize}
3456\item
3457A project has additional meta info described in Do.prj file
3458\item
3459A project may be dependent on other packages
3460\item
3461A project can be transformed into a package for distribution
3462\item
3463A project can generate one or more executable binaries
3464\end{itemize}
3465\end{itemize}
3466
3467
3468\subsubsection{Module File Organization}
3469
3470The rules of this section are the conventions to organize module files in one package.
3471
3472The file location of a module in a package must match the module/submodule naming hierarchy.
3473The names separated by slash "/" must match the directory levels.
3474If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory.
3475The file can be put inside its parent module's sub-directory with the sub module's name as the file name.
3476
3477Here is an example of a package, util.
3478\begin{lstlisting}
3479+ util
3480        Do.prj #package description file
3481        heap.do #Case 1: module heap;
3482        list.do #Case 1: mdoule list;
3483        ring.do #Case 1: module ring;
3484        + string #Case 2
3485        impl1.do #module string;
3486        + std
3487        vector.do
3488        list.do
3489        + array #Case 3
3490        array1.do #module std/array;
3491        array2.do #module std/array;
3492        sequence.do #Case 4, module std/sequence;
3493        test.do #Case 5
3494\end{lstlisting}
3495
3496
3497\begin{itemize}
3498\item
3499Case 1: Each individual file implements a module
3500\item
3501Case 2: Put the implementation of a module under the sub-directory, but there is only one file
3502\item
3503Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module
3504\item
3505Case 4: One file to express one aggregation
3506\item
3507Case 5: The file does not belong to any module; It is used for testing purpose
3508\end{itemize}
3509
3510The example only uses source code, ".do" files, to show the module file organization.
3511Other module packaging formats, like binary, must also follow the same rules.
3512
3513
3514\subsubsection{Module File Format}
3515
3516\CFA supports different types of module file formats.
3517
3518\begin{itemize}
3519\item
3520Pure source code format: The files should be organized following the previous section's definition.
3521\item
3522IR format (TBD): The \CFA compiler IR format, similar to the source code format
3523\item
3524Binary format, including ".a" static library or ".so" dynamic linkage library
3525\begin{itemize}
3526\item
3527The file's name must match the right level's module name defined in the previous section
3528\item
3529E.g. "util.so" includes all modules for the package util.
3530\item
3531E.g. "string.so" under the package directory to include files belonging to "module string;"
3532\end{itemize}
3533\item
3534Archive format
3535\begin{itemize}
3536\item
3537The archive is named as ".dar", and is a zip archive of the source code or the binary for a package
3538\item
3539E.g. "util.dar" is the whole package for util package including the package direction file
3540\end{itemize}
3541\item
3542Hybrid format
3543\begin{itemize}
3544\item
3545A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format
3546\item
3547The only limitation is that the names of the files must match the module location names defined in previous section
3548\end{itemize}
3549\end{itemize}
3550
3551
3552\subsection{Package and Module Locating}
3553
3554The 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.
3555If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries.
3556
3557When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order:
3558
3559\begin{enumerate}
3560\item
3561This source file's directory tree, which is typically the project's src directory
3562\item
3563All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory
3564\item
3565The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable
3566\item
3567The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory
3568\item
3569If 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
3570\end{enumerate}
3571
3572The module found first in a package will shadow the modules with the same name in the later packages in the search sequence.
3573
3574
3575\subsubsection{Dependent Package}
3576
3577Dependent packages are those packages containing modules that the current project's source code will import from.
3578Dependent packages are defined implicitly or explicitly in one \CFA project.
3579All of the packages under the current project's pkg directory are implicitly dependent packages.
3580For others, the dependent packages must be defined in the project's Do.prj file.
3581
3582
3583\subsubsection{Package and Module Locating Example}
3584
3585\begin{lstlisting}
3586# A project's source code tree
3587
3588--------------------------------------
3589
3590+ testProject
3591        Do.prj
3592        + src
3593        main.do
3594        + pkg
3595        + security-1.1
3596        Do.prj
3597        security.do #module security
3598
3599--------------------------------------
3600
3601# Do.prj
3602
3603--------------------------------------
3604
3605[dependences]
3606std
3607util = "0.2"
3608
3609--------------------------------------
3610
3611# main.do
3612
3613---------------------------------------
3614
3615import security;
3616import std/vector;
3617import container;
3618
3619----------------------------------------
3620\end{lstlisting}
3621
3622
3623\begin{lstlisting}
3624# pkg directory's source code tree
3625
3626-----------------------------------------
3627
3628+ pkg
3629        + std-1.0
3630        Do.prj
3631        vector.do #module std/vector;
3632        queue.do #module std/queue;
3633        + std-1.1
3634        Do.prj
3635        vector.do #module std/vector;
3636        queue.do #module std/queue;
3637        list.do #module std/list;
3638        + util-0.1
3639        Do.prj
3640        container.do #module container;
3641        + security-1.0
3642        security.do #module security;
3643------------------------------------------
3644\end{lstlisting}
3645
3646
3647During the compiling of main.do file import security;
3648The security module appears in both the local security-1.1 package, and the global security-1.0 package.
3649According to the locating sequence, the local security module in security-1.1 will be used.
3650And because the security-1.1 package is under local's pkg directory.
3651No dependence description is required in the project Do.prj file.
3652
3653import std/vector;
3654
3655The 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.
3656
3657import container;
3658
3659The 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.
3660The builder tool then will try to retrieve it from the web and store it in the global pkg directory.
3661After that, the container module from the newly downloaded package will be used in the compilation.
3662\end{comment}
3663
3664
3665\section{Comparison with Other Languages}
3666
3667\CFA is one of many languages that attempts to improve upon C.
3668In developing \CFA, many other languages were consulted for ideas, constructs, and syntax.
3669Therefore, it is important to show how these languages each compare with Do.
3670In 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}.
3671
3672
3673\subsection[Comparing Key Features of CFA]{Comparing Key Features of \CFA}
3674
3675
3676{% local change to lstlising to reduce font size
3677
3678
3679\lstset{basicstyle=\linespread{0.9}\sf\relsize{-2}}
3680
3681
3682\subsubsection{Constructors and Destructors}
3683
3684\begin{flushleft}
3685\begin{tabular}{@{}l|l|l|l@{}}
3686\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3687\hline
3688\begin{lstlisting}
3689struct Line {
3690        float lnth;
3691}
3692// default constructor
3693void ?{}( Line * l ) {
3694        l->lnth = 0.0;
3695        sout | "default" | endl;
3696}
3697
3698
3699// constructor with length
3700void ?{}( Line * l, float lnth ) {
3701        l->lnth = lnth;
3702        sout | "lnth" | l->lnth | endl;
3703
3704}
3705
3706// destructor
3707void ^?() {
3708        sout | "destroyed" | endl;
3709        l.lnth = 0.0;
3710}
3711
3712// usage
3713Line line1;
3714Line line2 = { 3.4 };
3715\end{lstlisting}
3716&
3717\begin{lstlisting}[language=C++]
3718class Line {
3719        float lnth;
3720
3721        // default constructor
3722        Line() {
3723                cout << "default" << endl;
3724                lnth = 0.0;
3725        }
3726
3727
3728        // constructor with lnth
3729        Line( float l ) {
3730                cout << "length " << length
3731                         << endl;
3732                length = l;
3733        }
3734
3735        // destructor
3736        ~Line() {
3737                cout << "destroyed" << endl;
3738                length = 0.0;
3739        }
3740}
3741// usage
3742Line line1;
3743Line line2( 3.4 );
3744\end{lstlisting}
3745&
3746\begin{lstlisting}[language=Golang]
3747type Line struct {
3748        length float32
3749}
3750// default constructor
3751func makeLine() Line {
3752        fmt.PrintLn( "default" )
3753        return Line{0.0}
3754}
3755
3756
3757// constructor with length
3758func makeLine( length float32 ) Line {
3759        fmt.Printf( "length %v", length )
3760
3761        return Line{length}
3762}
3763
3764// no destructor
3765
3766
3767
3768
3769
3770// usage
3771line1 := makeLine()
3772line2 := makeLine( 3.4 )
3773\end{lstlisting}
3774&
3775\begin{lstlisting}
3776struct Line {
3777        length: f32
3778}
3779// default constructor
3780impl Default for Line {
3781        fn default () -> Line {
3782                println!( "default" );
3783                Line{ length: 0.0 }
3784        }
3785}
3786// constructor with length
3787impl Line {
3788        fn make( len: f32 ) -> Line {
3789                println!( "length: {}", len );
3790                Line{ length: len }
3791        }
3792}
3793// destructor
3794impl Drop for Line {
3795        fn drop( &mut self ) {
3796                self.length = 0.0
3797        }
3798}
3799// usage
3800let line1:Line = Default::default();
3801Line line2( 3.4 );
3802\end{lstlisting}
3803\end{tabular}
3804\end{flushleft}
3805
3806
3807\subsubsection{Operator Overloading}
3808
3809\begin{flushleft}
3810\begin{tabular}{@{}l|l|l|l@{}}
3811\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3812\hline
3813\begin{lstlisting}
3814struct Cpx {
3815        double re, im;
3816};
3817// overload addition operator
3818Cpx ?+?( Cpx l, const Cpx r ) {
3819        return (Cpx){l.re+l.im, l.im+r.im};
3820}
3821Cpx a, b, c;
3822c = a + b;
3823\end{lstlisting}
3824&
3825\begin{lstlisting}
3826struct Cpx {
3827        double re, im;
3828};
3829// overload addition operator
3830Cpx operator+( Cpx l, const Cpx r ) {
3831        return (Cpx){l.re+l.im, l.im+r.im};
3832}
3833Cpx a, b, c;
3834c = a + b;
3835\end{lstlisting}
3836&
3837\begin{lstlisting}
3838// no operator overloading
3839
3840
3841
3842
3843
3844
3845
3846\end{lstlisting}
3847&
3848\begin{lstlisting}
3849struct Cpx {
3850        re: f32,
3851        im: f32
3852}
3853// overload addition operator
3854impl Add for Cpx {
3855        type Output = Cpx
3856        fn add(self, r: Cpx) -> Cpx {
3857                let mut res = Cpx{re: 0.0, im: 0.0};
3858                res.re = self.re + r.re;
3859                res.im = self.im + r.im;
3860                return res
3861        }
3862}
3863let (a, b, mut c) = ...;
3864c = a + b
3865\end{lstlisting}
3866\end{tabular}
3867\end{flushleft}
3868
3869
3870\subsubsection{Calling C Functions}
3871
3872\begin{flushleft}
3873\begin{tabular}{@{}l|l|l@{}}
3874\multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}   \\
3875\hline
3876\begin{lstlisting}[boxpos=t]
3877extern "C" {
3878#include <sys/types.h>
3879#include <sys/stat.h>
3880#include <unistd.h>
3881}
3882size_t fileSize( const char *path ) {
3883        struct stat s;
3884        stat(path, &s);
3885        return s.st_size;
3886}
3887\end{lstlisting}
3888&
3889\begin{lstlisting}[boxpos=t]
3890/*
3891#cgo
3892#include <sys/types.h>
3893#include <sys/stat.h>
3894#include <unistd.h>
3895*/
3896import "C"
3897import "unsafe"
3898
3899func fileSize(path string) C.size_t {
3900        var buf C.struct_stat
3901        c_string := C.CString(path)
3902        C.stat(p, &buf)
3903        C.free(unsafe.Pointer(c_string))
3904        return buf._st_size
3905}
3906\end{lstlisting}
3907&
3908\begin{lstlisting}[boxpos=t]
3909use libc::{c_int, size_t};
3910// translated from sys/stat.h
3911#[repr(C)]
3912struct stat_t {
3913        ...
3914        st_size: size_t,
3915        ...
3916}
3917#[link(name = "libc")]
3918extern {
3919        fn stat(path: *const u8,
3920        buf: *mut stat_t) -> c_int;
3921}
3922fn fileSize(path: *const u8) -> size_t
3923{
3924        unsafe {
3925                let mut buf: stat_t = uninit();
3926                stat(path, &mut buf);
3927                buf.st_size
3928        }
3929}
3930\end{lstlisting}
3931\end{tabular}
3932\end{flushleft}
3933
3934
3935\subsubsection{Generic Functions}
3936
3937\begin{flushleft}
3938\begin{tabular}{@{}l|l|l|l@{}}
3939\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
3940\hline
3941\begin{lstlisting}
3942generic(type T, type N |
3943        { int ?<?(N, N); })
3944T *maximize(N (*f)(const T&),
3945        int n, T *a) {
3946        T *bestX = NULL;
3947        N bestN;
3948        for (int i = 0; i < n; i++) {
3949        N curN = f(a[i]);
3950        if (bestX == NULL ||
3951        curN > bestN) {
3952        bestX = &a[i]; bestN = curN;
3953        }
3954        }
3955        return bestX;
3956}
3957
3958string *longest(int n, string *p)
3959{
3960        return maximize(length, n, p);
3961}
3962\end{lstlisting}
3963&
3964\begin{lstlisting}
3965template<typename T, typename F>
3966T *maximize(const F &f,
3967        int n, T *a) {
3968        typedef decltype(f(a[0])) N;
3969        T *bestX = NULL;
3970        N bestN;
3971        for (int i = 0; i < n; i++) {
3972        N curN = f(a[i]);
3973        if (bestX == NULL || curN > bestN)
3974        {
3975        bestX = &a[i]; bestN = curN;
3976        }
3977        }
3978        return bestX;
3979}
3980
3981string *longest(int n, string *p) {
3982        return maximize(
3983        [](const string &s) {
3984        return s.length();
3985        }, n, p);
3986}
3987\end{lstlisting}
3988&
3989\begin{lstlisting}
3990// Go does not support generics!
3991func maximize(
3992        gt func(interface{}, interface{}) bool,
3993        f func(interface{}) interface{},
3994        a []interface{}) interface{} {
3995        var bestX interface{} = nil
3996        var bestN interface{} = nil
3997        for _, x := range a {
3998        curN := f(x)
3999        if bestX == nil || gt(curN, bestN)
4000        {
4001        bestN = curN
4002        bestX = x
4003        }
4004        }
4005        return bestX
4006}
4007
4008func longest(
4009        a []interface{}) interface{} {
4010        return maximize(
4011        func(a, b interface{}) bool {
4012        return a.(int) > b.(int) },
4013        func(s interface{}) interface{} {
4014        return len(s.(string)) },
4015        a).(string)
4016}
4017\end{lstlisting}
4018&
4019\begin{lstlisting}
4020use std::cmp::Ordering;
4021
4022fn maximize<N: Ord + Copy, T, F:
4023Fn(&T) -> N>(f: F, a: &Vec<T>) ->
4024Option<&T> {
4025        let mut best_x: Option<&T> = None;
4026        let mut best_n: Option<N> = None;
4027        for x in a {
4028        let n = f(x);
4029        if (match best_n { None => true,
4030        Some(bn) =>
4031        n.cmp(&bn) == Ordering::Greater })
4032        {
4033        best_x = Some(x);
4034        best_n = Some(n);
4035        }
4036        }
4037        return best_x
4038}
4039
4040fn longest(a: &Vec<String>) ->
4041        Option<&String> {
4042        return
4043        maximize(|x: &String| x.len(), a)
4044}
4045\end{lstlisting}
4046\end{tabular}
4047\end{flushleft}
4048
4049
4050\begin{comment}
4051\subsubsection{Modules / Packages}
4052
4053\begin{lstlisting}
4054\CFA
4055\CC
4056
4057
4058module example/M;
4059
4060export int inc(int val) {
4061        return val + 1;
4062}
4063
4064
4065
4066
4067--------------------------------------
4068//Use the module in another file
4069import example/M;
4070int main() {
4071        print(M.inc(100));
4072        return 0;
4073}
4074// Using \CC17 module proposal
4075
4076module example.M;
4077
4078export {
4079        int inc(int val);
4080}
4081
4082int inc(inv val) {
4083        return val + 1;
4084}
4085--------------------------------------
4086// Use the module in another file
4087import example.M;
4088int main() {
4089        cout << inc(100) << endl;
4090        return 0;
4091}
4092
4093Go
4094Rust
4095package example/M;
4096
4097func Inc(val int32) int32 {
4098        // Capitalization indicates exported
4099        return val + 100
4100}
4101
4102
4103--------------------------------------
4104//Use the package in another file
4105package main
4106import .fmt.
4107import "example/M"
4108
4109func main() int32 {
4110        fmt.Printf(.%v., M.Inc(100))
4111}
4112pub mod example {
4113        pub mod M {
4114        pub inc(val i32) -> i32 {
4115        return val + 100;
4116        }
4117        }
4118}
4119
4120--------------------------------------
4121//Use the module in another file
4122use example::M;
4123
4124
4125
4126fn main() {
4127        println!(.{}., M::inc(100));
4128}
4129\end{lstlisting}
4130\end{comment}
4131
4132
4133\subsubsection{Parallel Tasks}
4134
4135\begin{flushleft}
4136\begin{tabular}{@{}l|l|l|l@{}}
4137\multicolumn{1}{c|}{\textbf{\CFA}}      & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}}      \\
4138\hline
4139\begin{lstlisting}
4140task Nonzero {
4141        int *data;
4142        int start;
4143        int end;
4144        int* res;
4145};
4146
4147void ?{}(Nonzero &a, int d[], int s,
4148        int e, int* subres) {
4149        // constructor
4150        a.data = d;
4151        a.start = s;
4152        a.end = e;
4153        a.res = subres;
4154}
4155
4156// implicitly spawn thread here
4157void ?()(NonzeroCounter &a) {
4158        int i;
4159        int nonzero = 0;
4160        for (i=start; c<end; ++i) {
4161        if(a.data[i]!=0){ nonzero++;}
4162        }
4163        *a.res = nonzero;
4164}
4165
4166int main() {
4167        int sz = ...
4168        int data[sz] = ...;
4169        int r1 = 0, r2=0;
4170        int res;
4171        { // create a scope for Nonzero
4172        Nonzero n1{data, 0, sz/2, &n1};
4173        Nonzero n2{data, sz/2, sz, &n2};
4174        n1();//spawn
4175        n2();//spawn
4176        }
4177        res = r1+r2;
4178        return res;
4179}
4180\end{lstlisting}
4181&
4182\begin{lstlisting}
4183#include <thread>
4184#include <mutex>
4185
4186std::mutex m;
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199void task(const vector<int>&v,
4200        int* res, size_t s,
4201        size_t e) {
4202        int non_zero = 0;
4203        for(size_t i = s; i < e; ++i){
4204        if(v[i]!=0) { non_zero++;}
4205        }
4206        std::unique_lock<mutex> lck {m};
4207        *res += non_zero;
4208}
4209
4210int main() {
4211        vector<int> data = ...; //data
4212        int res = 0;
4213        std::thread t1 {task, ref(data),
4214        &res, 0,
4215        data.size()/2};
4216        std::thread t2 {task, ref(data),
4217        &res, data.size()/2,
4218        data.size()};
4219        t1.join();
4220        t2.join();
4221        return res;
4222}
4223\end{lstlisting}
4224&
4225\begin{lstlisting}
4226package main
4227
4228import "fmt"
4229
4230func nonzero(data []int, c chan int) {
4231        nz := 0
4232        for _, v:=range data {
4233        if(v!=0) { nz := nz+1 }
4234        }
4235        c <- nz
4236}
4237
4238func main() {
4239        sz := ...
4240        data := make([]int, sz)
4241        ... // data init
4242        go nonzero(data[:len(data)/2], c)
4243        go nonzero(data[len(data)/2:], c)
4244        n1, n2 := <-c, <-c
4245        res := n1 + n2
4246        fmt.Println(res)
4247}
4248\end{lstlisting}
4249&
4250\begin{lstlisting}
4251use std::thread;
4252use std::sync:mpsc::channel;
4253
4254fn main() {
4255        let sz = ...;
4256        let mut data:Vec<i32> =
4257        Vec::with_capacity(sz as usize);
4258        ... //init data
4259        let (tx, rx) = channel();
4260        for i in 0..1 {
4261        let tx = tx.clone();
4262        let data = data.clone()
4263        thread::spawn(move|| {
4264        let mut nz := 0;
4265        let mut s = 0;
4266        let mut e = sz / 2;
4267        if i == 1 {
4268        s = sz/2;
4269        e = data.len();
4270        }
4271        for i in s..(e - 1) {
4272        if data[i] != 0 (
4273        nz = nz + 1
4274        }
4275        }
4276        tx.send(nz).unwrap();
4277        });
4278        }
4279        let res = rx.recv().unwrap() +
4280        rx.recv().unwrap();
4281        println!(.{}., res);
4282}
4283\end{lstlisting}
4284\end{tabular}
4285\end{flushleft}
4286
4287}% local change to lstlising to reduce font size
4288
4289
4290\subsection{Summary of Language Comparison}
4291
4292
4293\subsubsection[C++]{\CC}
4294
4295\Index*[C++]{\CC} is a general-purpose programming language.
4296It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia)
4297
4298The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do.
4299\CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data.
4300\CFA uses modules instead to perform these same tasks.
4301Classes in \CC also enable inheritance among types.
4302Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility.
4303There 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).
4304
4305Overloading 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.
4306References and exceptions in \CFA are heavily based on the same features from \CC.
4307The mechanism for interoperating with C code in \CFA is also borrowed from \CC.
4308
4309Both \CFA and \CC provide generics, and the syntax is quite similar.
4310The 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.
4311This means that a generic function can be defined in a compiled library, and still be used as expected from source.
4312
4313
4314\subsubsection{Go}
4315
4316\Index*{Go}, also commonly referred to as golang, is a programming language developed at Google in 2007 [.].
4317It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type
4318safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia)
4319
4320Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned.
4321Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction.
4322Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse.
4323Both 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.
4324
4325Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks.
4326\CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection.
4327This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead.
4328
4329
4330\subsubsection{Rust}
4331
4332\Index*{Rust} is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research.
4333It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles.
4334
4335The primary focus of Rust is in safety, especially in concurrent programs.
4336To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety.
4337This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead.
4338
4339Aside from those key differences, Rust and \CFA also have several similarities.
4340Both languages support no overhead interoperability with C and have minimal runtimes.
4341Both languages support inheritance and polymorphism through the use of interfaces (traits).
4342
4343
4344\subsubsection{D}
4345
4346The \Index*{D} programming language is an object-oriented, imperative, multi-paradigm system programming
4347language created by Walter Bright of Digital Mars and released in 2001. [.]
4348Though 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.
4349
4350D and \CFA both start with C and add productivity features.
4351The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces.
4352D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces.
4353Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates.
4354D does not have any built-in concurrency constructs in the
4355language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency.
4356
4357
4358\appendix
4359
4360
4361\section{Incompatible}
4362
4363The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{ANSI14:C++}.
4364
4365\begin{enumerate}
4366\item
4367\begin{description}
4368\item[Change:] add new keywords \\
4369New keywords are added to \CFA.
4370\item[Rationale:] keywords added to implement new semantics of \CFA.
4371\item[Effect on original feature:] change to semantics of well-defined feature. \\
4372Any ISO C programs using these keywords as identifiers are invalid \CFA programs.
4373\item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism:
4374\begin{lstlisting}
4375int `otype` = 3;                                // make keyword an identifier
4376double `choose` = 3.5;
4377\end{lstlisting}
4378Programs can be converted automatically by enclosing keyword identifiers in backquotes, and the backquotes can be remove later when the identifier name is changed.
4379Clashes in C system libraries (include files) can be handled automatically using preprocessor, ©#include_next© and ©-Ifilename©:
4380\begin{lstlisting}
4381// include file uses the CFA keyword "otype".
4382#if ! defined( otype )                  // nesting ?
4383#define otype `otype`
4384#define __CFA_BFD_H__
4385#endif // ! otype
4386
4387#include_next <bfd.h>                   // must have internal check for multiple expansion
4388
4389#if defined( otype ) && defined( __CFA_BFD_H__ )        // reset only if set
4390#undef otype
4391#undef __CFA_BFD_H__
4392#endif // otype && __CFA_BFD_H__
4393\end{lstlisting}
4394\item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare.
4395\end{description}
4396
4397\item
4398\begin{description}
4399\item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading:
4400\begin{lstlisting}
4401int rtn( int i );
4402int rtn( char c );
4403rtn( 'x' );                                             // programmer expects 2nd rtn to be called
4404\end{lstlisting}
4405\item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first.
4406In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character.
4407\begin{lstlisting}
4408sout | 'x' | " " | (int)'x' | endl;
4409x 120
4410\end{lstlisting}
4411Having to cast ©'x'© to ©char© is non-intuitive.
4412\item[Effect on original feature:] change to semantics of well-defined feature that depend on:
4413\begin{lstlisting}
4414sizeof( 'x' ) == sizeof( int )
4415\end{lstlisting}
4416no long work the same in \CFA programs.
4417\item[Difficulty of converting:] simple
4418\item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©.
4419\end{description}
4420
4421\item
4422\begin{description}
4423\item[Change:] make string literals ©const©:
4424\begin{lstlisting}
4425char * p = "abc";                               // valid in C, deprecated in §\CFA§
4426char * q = expr ? "abc" : "de"; // valid in C, invalid in §\CFA§
4427\end{lstlisting}
4428The type of a string literal is changed from ©[] char© to ©const [] char©.
4429Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©.
4430\item[Rationale:] This change is a safety issue:
4431\begin{lstlisting}
4432char * p = "abc";
4433p[0] = 'w';                                             // segment fault or change constant literal
4434\end{lstlisting}
4435The same problem occurs when passing a string literal to a routine that changes its argument.
4436\item[Effect on original feature:] change to semantics of well-defined feature.
4437\item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©.
4438\item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare.
4439\end{description}
4440
4441\item
4442\begin{description}
4443\item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope:
4444\begin{lstlisting}
4445int i;                                                  // forward definition
4446int *j = ®&i®;                                  // forward reference, valid in C, invalid in §\CFA§
4447int i = 0;                                              // definition
4448\end{lstlisting}
4449is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed.
4450This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example,
4451\begin{lstlisting}
4452struct X { int i; struct X *next; };
4453static struct X a;                              // forward definition
4454static struct X b = { 0, ®&};        // forward reference, valid in C, invalid in §\CFA§
4455static struct X a = { 1, &b };  // definition
4456\end{lstlisting}
4457\item[Rationale:] avoids having different initialization rules for builtin types and userdefined types.
4458\item[Effect on original feature:] change to semantics of well-defined feature.
4459\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.
4460\item[How widely used:] seldom
4461\end{description}
4462
4463\item
4464\begin{description}
4465\item[Change:] have ©struct© introduce a scope for nested types
4466In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing
4467Example:
4468\begin{lstlisting}
4469enum ®Colour® { R, G, B, Y, C, M };
4470struct Person {
4471        enum ®Colour® { R, G, B };      // nested type
4472        struct Face {                           // nested type
4473                ®Colour® Eyes, Hair;            // type defined outside (1 level)
4474        };
4475        ß.ß®Colour® shirt;                              // type defined outside (top level)
4476        ®Colour® pants;                         // type defined same level
4477        Face looks[10];                         // type defined same level
4478};
4479®Colour® c = R;                                 // type/enum defined same level
4480Personß.ß®Colour® pc = Personß.ßR;      // type/enum defined inside
4481Personß.ßFace pretty;                           // type defined inside
4482\end{lstlisting}
4483\item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism.
4484\item[Effect on original feature:] change to semantics of well-defined feature.
4485\item[Difficulty of converting:] Semantic transformation.
4486\item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version.
4487
4488\CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC}.
4489Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''.
4490Given 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.
4491\end{description}
4492
4493\item
4494\begin{description}
4495\item[Change:] In C++, the name of a nested class is local to its enclosing class.
4496\item[Rationale:] C++ classes have member functions which require that classes establish scopes.
4497\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:
4498\begin{lstlisting}
4499struct Y; // struct Y and struct X are at the same scope
4500struct X {
4501struct Y { /* ... */ } y;
4502};
4503\end{lstlisting}
4504All 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.
4505Note: this is a consequence of the difference in scope rules, which is documented in 3.3.
4506\item[How widely used:] Seldom.
4507\end{description}
4508
4509\item
4510\begin{description}
4511\item[Change:] comma expression is disallowed as subscript
4512\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.
4513\item[Effect on original feature:] change to semantics of well-defined feature.
4514\item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]©
4515\item[How widely used:] seldom.
4516\end{description}
4517\end{enumerate}
4518
4519
4520\section{I/O Library}
4521\label{s:IOLibrary}
4522\index{input/output library}
4523
4524The 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.
4525The common case is printing out a sequence of variables separated by whitespace.
4526\begin{quote2}
4527\begin{tabular}{@{}l@{\hspace{3em}}l@{}}
4528\multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}}        & \multicolumn{1}{c}{\textbf{\CC}}      \\
4529\begin{lstlisting}
4530int x = 0, y = 1, z = 2;
4531®sout® ®|® x ®|® y ®|® z ®| endl®;
4532\end{lstlisting}
4533&
4534\begin{lstlisting}
4535
4536cout << x << " " << y << " " << z << endl;
4537\end{lstlisting}
4538\end{tabular}
4539\end{quote2}
4540The \CFA form has half as many characters as the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators.
4541
4542The logical-or operator is used because it is the lowest-priority overloadable operator, other than assignment.
4543Therefore, fewer output expressions require parenthesis.
4544\begin{quote2}
4545\begin{tabular}{@{}ll@{}}
4546\textbf{\CFA:}
4547&
4548\begin{lstlisting}
4549sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
4550\end{lstlisting}
4551\\
4552\textbf{\CC:}
4553&
4554\begin{lstlisting}
4555cout << x * 3 << y + 1 << (z << 2) << (x == y) << (x | y) << (x || y) << (x > z ? 1 : 2) << endl;
4556\end{lstlisting}
4557\end{tabular}
4558\end{quote2}
4559Finally, the logical-or operator has a link with the Shell pipe-operator for moving data, although data flows in the opposite direction.
4560
4561The implicit separator\index{I/O separator} character (space/blank) is a separator not a terminator.
4562The rules for implicitly adding the separator are:
4563\begin{enumerate}
4564\item
4565A separator does not appear at the start or end of a line.
4566\begin{lstlisting}[belowskip=0pt]
4567sout | 1 | 2 | 3 | endl;
4568\end{lstlisting}
4569\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
45701 2 3
4571\end{lstlisting}
4572\item
4573A separator does not appear before or after a character literal or variable.
4574\begin{lstlisting}
4575sout | '1' | '2' | '3' | endl;
4576123
4577\end{lstlisting}
4578\item
4579A separator does not appear before or after a null (empty) C string
4580\begin{lstlisting}
4581sout | 1 | "" | 2 | "" | 3 | endl;
4582123
4583\end{lstlisting}
4584which is a local mechanism to disable insertion of the separator character.
4585\item
4586A separator does not appear before a C string starting with the (extended) \Index{ASCII}\index{ASCII!extended} characters: \lstinline[mathescape=off]@([{$£¥¡¿«@
4587%$
4588\begin{lstlisting}[mathescape=off]
4589sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x $" | 4 | "x £" | 5 | "x ¥" | 6 | "x ¡" | 7 | "x ¿" | 8 | "x «" | 9 | endl;
4590\end{lstlisting}
4591%$
4592\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4593x (1 x [2 x {3 x $4 x £5 x ¥6 x ¡7 x ¿8 x «9
4594\end{lstlisting}
4595%$
4596\item
4597A seperator does not appear after a C string ending with the (extended) \Index{ASCII}\index{ASCII!extended} characters: ©,.:;!?)]}%¢»©
4598\begin{lstlisting}[belowskip=0pt]
4599sout | 1 | ", x" | 2 | ". x" | 3 | ": x" | 4 | "; x" | 5 | "! x" | 6 | "? x" | 7 | ") x" | 8 | "] x" | 9 | "} x"
4600         | 10 | "% x" | 11 | "¢ x" | 12 | "» x" | endl;
4601\end{lstlisting}
4602\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
46031, x 2. x 3: x 4; x 5! x 6? x 7) x 8] x 9} x 10% x 11¢ 12»
4604\end{lstlisting}
4605\item
4606A 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@
4607\begin{lstlisting}[belowskip=0pt]
4608sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x" | "x " | 4 | " x" | "x\t" | 1 | "\tx" | endl;
4609\end{lstlisting}
4610\begin{lstlisting}[mathescape=off,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt]
4611x`1`x'2'x"3"x x 4 x x   1       x
4612\end{lstlisting}
4613\end{enumerate}
4614The following \CC-style \Index{manipulator}s allow further control over implicit seperation.
4615\begin{lstlisting}[mathescape=off,belowskip=0pt]
4616sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
4617\end{lstlisting}
4618\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4619 1 2 3
4620\end{lstlisting}
4621\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4622sout | 1 | sepOff | 2 | 3 | endl;                       // turn off implicit separator temporarily
4623\end{lstlisting}
4624\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
462512 3
4626\end{lstlisting}
4627\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4628sout | sepDisable | 1 | 2 | 3 | endl;           // turn off implicit separation, affects all subsequent prints
4629\end{lstlisting}
4630\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4631123
4632\end{lstlisting}
4633\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4634sout | 1 | sepOn | 2 | 3 | endl;                        // turn on implicit separator temporarily
4635\end{lstlisting}
4636\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
46371 23
4638\end{lstlisting}
4639\begin{lstlisting}[mathescape=off,aboveskip=0pt,belowskip=0pt]
4640sout | sepEnable | 1 | 2 | 3 | endl;            // turn on implicit separation, affects all subsequent prints
4641\end{lstlisting}
4642\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt]
4643 1 2 3
4644\end{lstlisting}
4645\begin{lstlisting}[mathescape=off,aboveskip=0pt,aboveskip=0pt,belowskip=0pt]
4646sepSet( sout, ", $" );                                          // change separator from " " to ", $"
4647sout | 1 | 2 | 3 | endl;
4648\end{lstlisting}
4649%$
4650\begin{lstlisting}[mathescape=off,showspaces=true,aboveskip=0pt]
46511, $2, $3
4652\end{lstlisting}
4653%$
4654\begin{comment}
4655#include <fstream>
4656
4657int main() {
4658        int x = 3, y = 5, z = 7;
4659        sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl;
4660        sout | 1 | 2 | 3 | endl;
4661        sout | '1' | '2' | '3' | endl;
4662        sout | 1 | "" | 2 | "" | 3 | endl;
4663        sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x $" | 4 | "x £" | 5 | "x ¥" | 6 | "x ¡" | 7 | "x ¿" | 8 | "x «" | 9 | endl;
4664        sout | 1 | ", x" | 2 | ". x" | 3 | ": x" | 4 | "; x" | 5 | "! x" | 6 | "? x" | 7 | ") x" | 8 | "] x" | 9 | "} x"
4665                 | 10 | "% x" | 11 | "¢ x" | 12 | "» x" | endl;
4666        sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x" | "x " | 4 | " x" | "x\t" | 1 | "\tx" | endl;
4667        sout | sepOn | 1 | 2 | 3 | sepOn | endl;        // separator at start of line
4668        sout | 1 | sepOff | 2 | 3 | endl;                       // turn off implicit separator temporarily
4669        sout | sepDisable | 1 | 2 | 3 | endl;           // turn off implicit separation, affects all subsequent prints
4670        sout | 1 | sepOn | 2 | 3 | endl;                        // turn on implicit separator temporarily
4671        sout | sepEnable | 1 | 2 | 3 | endl;            // turn on implicit separation, affects all subsequent prints
4672        sepSet( sout, ", $" );                                          // change separator from " " to ", $"
4673        sout | 1 | 2 | 3 | endl;
4674
4675}
4676
4677// Local Variables: //
4678// tab-width: 4 //
4679// End: //
4680\end{comment}
4681%$
4682
4683
4684\section{Standard Library}
4685\label{s:StandardLibrary}
4686
4687The goal of the \CFA standard-library is to wrap many of the existing C library-routines that are explicitly polymorphic into implicitly polymorphic versions.
4688
4689
4690\subsection{malloc}
4691
4692\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4693forall( otype T ) T * malloc( void );§\indexc{malloc}§
4694forall( otype T ) T * malloc( char fill );
4695forall( otype T ) T * malloc( T * ptr, size_t size );
4696forall( otype T ) T * malloc( T * ptr, size_t size, unsigned char fill );
4697forall( otype T ) T * calloc( size_t nmemb );§\indexc{calloc}§
4698forall( otype T ) T * realloc( T * ptr, size_t size );§\indexc{ato}§
4699forall( otype T ) T * realloc( T * ptr, size_t size, unsigned char fill );
4700
4701forall( otype T ) T * aligned_alloc( size_t alignment );§\indexc{ato}§
4702forall( otype T ) T * memalign( size_t alignment );             // deprecated
4703forall( otype T ) int posix_memalign( T ** ptr, size_t alignment );
4704
4705forall( otype T ) T * memset( T * ptr, unsigned char fill ); // use default value '\0' for fill
4706forall( otype T ) T * memset( T * ptr );                                // remove when default value available
4707\end{lstlisting}
4708\
4709
4710\subsection{ato / strto}
4711
4712\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4713int ato( const char * ptr );§\indexc{ato}§
4714unsigned int ato( const char * ptr );
4715long int ato( const char * ptr );
4716unsigned long int ato( const char * ptr );
4717long long int ato( const char * ptr );
4718unsigned long long int ato( const char * ptr );
4719float ato( const char * ptr );
4720double ato( const char * ptr );
4721long double ato( const char * ptr );
4722float _Complex ato( const char * ptr );
4723double _Complex ato( const char * ptr );
4724long double _Complex ato( const char * ptr );
4725
4726int strto( const char * sptr, char ** eptr, int base );
4727unsigned int strto( const char * sptr, char ** eptr, int base );
4728long int strto( const char * sptr, char ** eptr, int base );
4729unsigned long int strto( const char * sptr, char ** eptr, int base );
4730long long int strto( const char * sptr, char ** eptr, int base );
4731unsigned long long int strto( const char * sptr, char ** eptr, int base );
4732float strto( const char * sptr, char ** eptr );
4733double strto( const char * sptr, char ** eptr );
4734long double strto( const char * sptr, char ** eptr );
4735float _Complex strto( const char * sptr, char ** eptr );
4736double _Complex strto( const char * sptr, char ** eptr );
4737long double _Complex strto( const char * sptr, char ** eptr );
4738\end{lstlisting}
4739\
4740
4741
4742\subsection{bsearch / qsort}
4743
4744\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4745forall( otype T | { int ?<?( T, T ); } )
4746T * bsearch( const T key, const T * arr, size_t dimension );§\indexc{bsearch}§
4747
4748forall( otype T | { int ?<?( T, T ); } )
4749void qsort( const T * arr, size_t dimension );§\indexc{qsort}§
4750\end{lstlisting}
4751\
4752
4753
4754\subsection{abs}
4755
4756\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4757char abs( char );§\indexc{abs}§
4758int abs( int );
4759long int abs( long int );
4760long long int abs( long long int );
4761float abs( float );
4762double abs( double );
4763long double abs( long double );
4764float abs( float _Complex );
4765double abs( double _Complex );
4766long double abs( long double _Complex );
4767\end{lstlisting}
4768\
4769
4770
4771\subsection{random}
4772
4773\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4774void rand48seed( long int s );§\indexc{rand48seed}§
4775char rand48();§\indexc{rand48}§
4776int rand48();
4777unsigned int rand48();
4778long int rand48();
4779unsigned long int rand48();
4780float rand48();
4781double rand48();
4782float _Complex rand48();
4783double _Complex rand48();
4784long double _Complex rand48();
4785\end{lstlisting}
4786\
4787
4788
4789\subsection{min / max / clamp / swap}
4790
4791\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4792forall( otype T | { int ?<?( T, T ); } )
4793T min( const T t1, const T t2 );§\indexc{min}§
4794
4795forall( otype T | { int ?>?( T, T ); } )
4796T max( const T t1, const T t2 );§\indexc{max}§
4797
4798forall( otype T | { T min( T, T ); T max( T, T ); } )
4799T clamp( T value, T min_val, T max_val );§\indexc{clamp}§
4800
4801forall( otype T )
4802void swap( T * t1, T * t2 );§\indexc{swap}§
4803\end{lstlisting}
4804\
4805
4806
4807\section{Math Library}
4808\label{s:Math Library}
4809
4810The 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.
4811
4812
4813\subsection{General}
4814
4815\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4816float fabs( float );§\indexc{fabs}§
4817double fabs( double );
4818long double fabs( long double );
4819float cabs( float _Complex );
4820double cabs( double _Complex );
4821long double cabs( long double _Complex );
4822
4823float ?%?( float, float );§\indexc{fmod}§
4824float fmod( float, float );
4825double ?%?( double, double );
4826double fmod( double, double );
4827long double ?%?( long double, long double );
4828long double fmod( long double, long double );
4829
4830float remainder( float, float );§\indexc{remainder}§
4831double remainder( double, double );
4832long double remainder( long double, long double );
4833
4834[ int, float ] remquo( float, float );§\indexc{remquo}§
4835float remquo( float, float, int * );
4836[ int, double ] remquo( double, double );
4837double remquo( double, double, int * );
4838[ int, long double ] remquo( long double, long double );
4839long double remquo( long double, long double, int * );
4840
4841[ int, float ] div( float, float );                                             // alternative name for remquo
4842float div( float, float, int * );§\indexc{div}§
4843[ int, double ] div( double, double );
4844double div( double, double, int * );
4845[ int, long double ] div( long double, long double );
4846long double div( long double, long double, int * );
4847
4848float fma( float, float, float );§\indexc{fma}§
4849double fma( double, double, double );
4850long double fma( long double, long double, long double );
4851
4852float fdim( float, float );§\indexc{fdim}§
4853double fdim( double, double );
4854long double fdim( long double, long double );
4855
4856float nan( const char * );§\indexc{nan}§
4857double nan( const char * );
4858long double nan( const char * );
4859\end{lstlisting}
4860\
4861
4862
4863\subsection{Exponential}
4864
4865\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4866float exp( float );§\indexc{exp}§
4867double exp( double );
4868long double exp( long double );
4869float _Complex exp( float _Complex );
4870double _Complex exp( double _Complex );
4871long double _Complex exp( long double _Complex );
4872
4873float exp2( float );§\indexc{exp2}§
4874double exp2( double );
4875long double exp2( long double );
4876float _Complex exp2( float _Complex );
4877double _Complex exp2( double _Complex );
4878long double _Complex exp2( long double _Complex );
4879
4880float expm1( float );§\indexc{expm1}§
4881double expm1( double );
4882long double expm1( long double );
4883
4884float log( float );§\indexc{log}§
4885double log( double );
4886long double log( long double );
4887float _Complex log( float _Complex );
4888double _Complex log( double _Complex );
4889long double _Complex log( long double _Complex );
4890
4891float log2( float );§\indexc{log2}§
4892double log2( double );
4893long double log2( long double );
4894float _Complex log2( float _Complex );
4895double _Complex log2( double _Complex );
4896long double _Complex log2( long double _Complex );
4897
4898float log10( float );§\indexc{log10}§
4899double log10( double );
4900long double log10( long double );
4901float _Complex log10( float _Complex );
4902double _Complex log10( double _Complex );
4903long double _Complex log10( long double _Complex );
4904
4905float log1p( float );§\indexc{log1p}§
4906double log1p( double );
4907long double log1p( long double );
4908
4909int ilogb( float );§\indexc{ilogb}§
4910int ilogb( double );
4911int ilogb( long double );
4912
4913float logb( float );§\indexc{logb}§
4914double logb( double );
4915long double logb( long double );
4916\end{lstlisting}
4917\
4918
4919
4920\subsection{Power}
4921
4922\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4923float sqrt( float );§\indexc{sqrt}§
4924double sqrt( double );
4925long double sqrt( long double );
4926float _Complex sqrt( float _Complex );
4927double _Complex sqrt( double _Complex );
4928long double _Complex sqrt( long double _Complex );
4929
4930float cbrt( float );§\indexc{cbrt}§
4931double cbrt( double );
4932long double cbrt( long double );
4933
4934float hypot( float, float );§\indexc{hypot}§
4935double hypot( double, double );
4936long double hypot( long double, long double );
4937
4938float pow( float, float );§\indexc{pow}§
4939double pow( double, double );
4940long double pow( long double, long double );
4941float _Complex pow( float _Complex, float _Complex );
4942double _Complex pow( double _Complex, double _Complex );
4943long double _Complex pow( long double _Complex, long double _Complex );
4944\end{lstlisting}
4945\
4946
4947
4948\subsection{Trigonometric}
4949
4950\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
4951float sin( float );§\indexc{sin}§
4952double sin( double );
4953long double sin( long double );
4954float _Complex sin( float _Complex );
4955double _Complex sin( double _Complex );
4956long double _Complex sin( long double _Complex );
4957
4958float cos( float );§\indexc{cos}§
4959double cos( double );
4960long double cos( long double );
4961float _Complex cos( float _Complex );
4962double _Complex cos( double _Complex );
4963long double _Complex cos( long double _Complex );
4964
4965float tan( float );§\indexc{tan}§
4966double tan( double );
4967long double tan( long double );
4968float _Complex tan( float _Complex );
4969double _Complex tan( double _Complex );
4970long double _Complex tan( long double _Complex );
4971
4972float asin( float );§\indexc{asin}§
4973double asin( double );
4974long double asin( long double );
4975float _Complex asin( float _Complex );
4976double _Complex asin( double _Complex );
4977long double _Complex asin( long double _Complex );
4978
4979float acos( float );§\indexc{acos}§
4980double acos( double );
4981long double acos( long double );
4982float _Complex acos( float _Complex );
4983double _Complex acos( double _Complex );
4984long double _Complex acos( long double _Complex );
4985
4986float atan( float );§\indexc{atan}§
4987double atan( double );
4988long double atan( long double );
4989float _Complex atan( float _Complex );
4990double _Complex atan( double _Complex );
4991long double _Complex atan( long double _Complex );
4992
4993float atan2( float, float );§\indexc{atan2}§
4994double atan2( double, double );
4995long double atan2( long double, long double );
4996
4997float atan( float, float );                                                             // alternative name for atan2
4998double atan( double, double );§\indexc{atan}§
4999long double atan( long double, long double );
5000\end{lstlisting}
5001\
5002
5003
5004\subsection{Hyperbolic}
5005
5006\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5007float sinh( float );§\indexc{sinh}§
5008double sinh( double );
5009long double sinh( long double );
5010float _Complex sinh( float _Complex );
5011double _Complex sinh( double _Complex );
5012long double _Complex sinh( long double _Complex );
5013
5014float cosh( float );§\indexc{cosh}§
5015double cosh( double );
5016long double cosh( long double );
5017float _Complex cosh( float _Complex );
5018double _Complex cosh( double _Complex );
5019long double _Complex cosh( long double _Complex );
5020
5021float tanh( float );§\indexc{tanh}§
5022double tanh( double );
5023long double tanh( long double );
5024float _Complex tanh( float _Complex );
5025double _Complex tanh( double _Complex );
5026long double _Complex tanh( long double _Complex );
5027
5028float asinh( float );§\indexc{asinh}§
5029double asinh( double );
5030long double asinh( long double );
5031float _Complex asinh( float _Complex );
5032double _Complex asinh( double _Complex );
5033long double _Complex asinh( long double _Complex );
5034
5035float acosh( float );§\indexc{acosh}§
5036double acosh( double );
5037long double acosh( long double );
5038float _Complex acosh( float _Complex );
5039double _Complex acosh( double _Complex );
5040long double _Complex acosh( long double _Complex );
5041
5042float atanh( float );§\indexc{atanh}§
5043double atanh( double );
5044long double atanh( long double );
5045float _Complex atanh( float _Complex );
5046double _Complex atanh( double _Complex );
5047long double _Complex atanh( long double _Complex );
5048\end{lstlisting}
5049\
5050
5051
5052\subsection{Error / Gamma}
5053
5054\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5055float erf( float );§\indexc{erf}§
5056double erf( double );
5057long double erf( long double );
5058float _Complex erf( float _Complex );
5059double _Complex erf( double _Complex );
5060long double _Complex erf( long double _Complex );
5061
5062float erfc( float );§\indexc{erfc}§
5063double erfc( double );
5064long double erfc( long double );
5065float _Complex erfc( float _Complex );
5066double _Complex erfc( double _Complex );
5067long double _Complex erfc( long double _Complex );
5068
5069float lgamma( float );§\indexc{lgamma}§
5070double lgamma( double );
5071long double lgamma( long double );
5072float lgamma( float, int * );
5073double lgamma( double, int * );
5074long double lgamma( long double, int * );
5075
5076float tgamma( float );§\indexc{tgamma}§
5077double tgamma( double );
5078long double tgamma( long double );
5079\end{lstlisting}
5080\
5081
5082
5083\subsection{Nearest Integer}
5084
5085\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5086float floor( float );§\indexc{floor}§
5087double floor( double );
5088long double floor( long double );
5089
5090float ceil( float );§\indexc{ceil}§
5091double ceil( double );
5092long double ceil( long double );
5093
5094float trunc( float );§\indexc{trunc}§
5095double trunc( double );
5096long double trunc( long double );
5097
5098float rint( float );§\indexc{rint}§
5099long double rint( long double );
5100long int rint( float );
5101long int rint( double );
5102long int rint( long double );
5103long long int rint( float );
5104long long int rint( double );
5105long long int rint( long double );
5106
5107long int lrint( float );§\indexc{lrint}§
5108long int lrint( double );
5109long int lrint( long double );
5110long long int llrint( float );
5111long long int llrint( double );
5112long long int llrint( long double );
5113
5114float nearbyint( float );§\indexc{nearbyint}§
5115double nearbyint( double );
5116long double nearbyint( long double );
5117
5118float round( float );§\indexc{round}§
5119long double round( long double );
5120long int round( float );
5121long int round( double );
5122long int round( long double );
5123long long int round( float );
5124long long int round( double );
5125long long int round( long double );
5126
5127long int lround( float );§\indexc{lround}§
5128long int lround( double );
5129long int lround( long double );
5130long long int llround( float );
5131long long int llround( double );
5132long long int llround( long double );
5133\end{lstlisting}
5134\
5135
5136
5137\subsection{Manipulation}
5138
5139\begin{lstlisting}[aboveskip=0pt,belowskip=0pt]
5140float copysign( float, float );§\indexc{copysign}§
5141double copysign( double, double );
5142long double copysign( long double, long double );
5143
5144float frexp( float, int * );§\indexc{frexp}§
5145double frexp( double, int * );
5146long double frexp( long double, int * );
5147
5148float ldexp( float, int );§\indexc{ldexp}§
5149double ldexp( double, int );
5150long double ldexp( long double, int );
5151
5152[ float, float ] modf( float );§\indexc{modf}§
5153float modf( float, float * );
5154[ double, double ] modf( double );
5155double modf( double, double * );
5156[ long double, long double ] modf( long double );
5157long double modf( long double, long double * );
5158
5159float nextafter( float, float );§\indexc{nextafter}§
5160double nextafter( double, double );
5161long double nextafter( long double, long double );
5162
5163float nexttoward( float, long double );§\indexc{nexttoward}§
5164double nexttoward( double, long double );
5165long double nexttoward( long double, long double );
5166
5167float scalbn( float, int );§\indexc{scalbn}§
5168double scalbn( double, int );
5169long double scalbn( long double, int );
5170
5171float scalbln( float, long int );§\indexc{scalbln}§
5172double scalbln( double, long int );
5173long double scalbln( long double, long int );
5174\end{lstlisting}
5175\
5176
5177
5178\section{Rational Numbers}
5179\label{s:RationalNumbers}
5180
5181Rational numbers are numbers written as a ratio, \ie as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers.
5182When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible.
5183
5184\begin{lstlisting}[belowskip=0pt]
5185// implementation
5186struct Rational {§\indexc{Rational}§
5187        long int numerator, denominator;                                        // invariant: denominator > 0
5188}; // Rational
5189
5190// constants
5191extern struct Rational 0;
5192extern struct Rational 1;
5193
5194// constructors
5195Rational rational();
5196Rational rational( long int n );
5197Rational rational( long int n, long int d );
5198
5199// getter/setter for numerator/denominator
5200long int numerator( Rational r );
5201long int numerator( Rational r, long int n );
5202long int denominator( Rational r );
5203long int denominator( Rational r, long int d );
5204
5205// comparison
5206int ?==?( Rational l, Rational r );
5207int ?!=?( Rational l, Rational r );
5208int ?<?( Rational l, Rational r );
5209int ?<=?( Rational l, Rational r );
5210int ?>?( Rational l, Rational r );
5211int ?>=?( Rational l, Rational r );
5212
5213// arithmetic
5214Rational -?( Rational r );
5215Rational ?+?( Rational l, Rational r );
5216Rational ?-?( Rational l, Rational r );
5217Rational ?*?( Rational l, Rational r );
5218Rational ?/?( Rational l, Rational r );
5219
5220// conversion
5221double widen( Rational r );
5222Rational narrow( double f, long int md );
5223
5224// I/O
5225forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * );
5226forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational );
5227\end{lstlisting}
5228
5229
5230\bibliographystyle{plain}
5231\bibliography{cfa}
5232
5233
5234\addcontentsline{toc}{section}{\indexname} % add index name to table of contents
5235\begin{theindex}
5236Italic page numbers give the location of the main entry for the referenced term.
5237Plain page numbers denote uses of the indexed term.
5238Entries for grammar non-terminals are italicized.
5239A typewriter font is used for grammar terminals and program identifiers.
5240\indexspace
5241\input{user.ind}
5242\end{theindex}
5243
5244
5245\end{document}
5246
5247% Local Variables: %
5248% tab-width: 4 %
5249% fill-column: 100 %
5250% compile-command: "make" %
5251% End: %
Note: See TracBrowser for help on using the repository browser.