source: doc/user/user.tex @ 245510f

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

update user manual and global latex macros

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