source: doc/user/user.tex @ a17e7b8

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

update section on pointer/reference

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