source: doc/user/user.tex @ 53ba273

aaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglergc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newstringwith_gc
Last change on this file since 53ba273 was 53ba273, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

switch from std=c99 to std=gnu99, update latex macros, refrat and extend user manual, update limits/iostream/fstream, add rational numbers

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