1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
2 | %% |
---|
3 | %% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo |
---|
4 | %% |
---|
5 | %% The contents of this file are covered under the licence agreement in the |
---|
6 | %% file "LICENCE" distributed with Cforall. |
---|
7 | %% |
---|
8 | %% user.tex -- |
---|
9 | %% |
---|
10 | %% Author : Peter A. Buhr |
---|
11 | %% Created On : Wed Apr 6 14:53:29 2016 |
---|
12 | %% Last Modified By : Peter A. Buhr |
---|
13 | %% Last Modified On : Sat Jul 1 17:19:42 2017 |
---|
14 | %% Update Count : 2495 |
---|
15 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
16 | |
---|
17 | % requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended |
---|
18 | |
---|
19 | \documentclass[twoside,11pt]{article} |
---|
20 | |
---|
21 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
22 | |
---|
23 | % Latex packages used in the document. |
---|
24 | \usepackage[T1]{fontenc} % allow Latin1 (extended ASCII) characters |
---|
25 | \usepackage{textcomp} |
---|
26 | \usepackage[latin1]{inputenc} |
---|
27 | |
---|
28 | \usepackage{fullpage,times,comment} |
---|
29 | \usepackage{epic,eepic} |
---|
30 | \usepackage{upquote} % switch curled `'" to straight |
---|
31 | \usepackage{calc} |
---|
32 | \usepackage{xspace} |
---|
33 | \usepackage{varioref} % extended references |
---|
34 | \usepackage{listings} % format program code |
---|
35 | \usepackage[flushmargin]{footmisc} % support label/reference in footnote |
---|
36 | \usepackage{latexsym} % \Box glyph |
---|
37 | \usepackage{mathptmx} % better math font with "times" |
---|
38 | \usepackage[usenames]{color} |
---|
39 | \usepackage[pagewise]{lineno} |
---|
40 | \renewcommand{\linenumberfont}{\scriptsize\sffamily} |
---|
41 | \input{common} % common CFA document macros |
---|
42 | \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref} |
---|
43 | \usepackage{breakurl} |
---|
44 | \renewcommand{\UrlFont}{\small\sf} |
---|
45 | |
---|
46 | % Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore |
---|
47 | % removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR |
---|
48 | % AFTER HYPERREF. |
---|
49 | \renewcommand{\_}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}} |
---|
50 | \renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}} |
---|
51 | |
---|
52 | \setlength{\topmargin}{-0.45in} % move running title into header |
---|
53 | \setlength{\headsep}{0.25in} |
---|
54 | |
---|
55 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
56 | |
---|
57 | \CFAStyle % use default CFA format-style |
---|
58 | |
---|
59 | % inline code ©...© (copyright symbol) emacs: C-q M-) |
---|
60 | % red highlighting ®...® (registered trademark symbol) emacs: C-q M-. |
---|
61 | % blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_ |
---|
62 | % green highlighting ¢...¢ (cent symbol) emacs: C-q M-" |
---|
63 | % LaTex escape §...§ (section symbol) emacs: C-q M-' |
---|
64 | % keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^ |
---|
65 | % math escape $...$ (dollar symbol) |
---|
66 | |
---|
67 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
68 | |
---|
69 | % Names used in the document. |
---|
70 | \newcommand{\Version}{\input{../../version}} |
---|
71 | \newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}} |
---|
72 | \newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}} |
---|
73 | \newcommand{\R}[1]{\Textbf{#1}} |
---|
74 | \newcommand{\B}[1]{{\Textbf[blue]{#1}}} |
---|
75 | \newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}} |
---|
76 | |
---|
77 | \newsavebox{\LstBox} |
---|
78 | |
---|
79 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
80 | |
---|
81 | \setcounter{secnumdepth}{3} % number subsubsections |
---|
82 | \setcounter{tocdepth}{3} % subsubsections in table of contents |
---|
83 | \makeindex |
---|
84 | |
---|
85 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
86 | |
---|
87 | \title{\Huge |
---|
88 | \vspace*{1in} |
---|
89 | \CFA (\CFL) User Manual \\ |
---|
90 | Version 1.0 \\ |
---|
91 | \vspace*{0.25in} |
---|
92 | \huge``describe not prescribe'' |
---|
93 | \vspace*{1in} |
---|
94 | }% title |
---|
95 | |
---|
96 | \author{ |
---|
97 | \huge \CFA Team \medskip \\ |
---|
98 | \Large Andrew Beach, Richard Bilson, Peter A. Buhr, Thierry Delisle, \smallskip \\ |
---|
99 | \Large Glen Ditchfield, Rodolfo G. Esteves, Aaron Moss, Rob Schluntz |
---|
100 | }% author |
---|
101 | |
---|
102 | \date{ |
---|
103 | DRAFT \\ \today |
---|
104 | }% date |
---|
105 | |
---|
106 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
107 | |
---|
108 | \begin{document} |
---|
109 | \pagestyle{headings} |
---|
110 | % changed after setting pagestyle |
---|
111 | \renewcommand{\sectionmark}[1]{\markboth{\thesection\quad #1}{\thesection\quad #1}} |
---|
112 | \renewcommand{\subsectionmark}[1]{\markboth{\thesubsection\quad #1}{\thesubsection\quad #1}} |
---|
113 | \pagenumbering{roman} |
---|
114 | \linenumbers % comment out to turn off line numbering |
---|
115 | |
---|
116 | \maketitle |
---|
117 | \thispagestyle{empty} |
---|
118 | \vspace*{\fill} |
---|
119 | \noindent |
---|
120 | \copyright\,2016 \CFA Project \\ \\ |
---|
121 | \noindent |
---|
122 | This work is licensed under the Creative Commons Attribution 4.0 International License. |
---|
123 | To view a copy of this license, visit {\small\url{http://creativecommons.org/licenses/by/4.0}}. |
---|
124 | \vspace*{1in} |
---|
125 | |
---|
126 | \clearpage |
---|
127 | \thispagestyle{plain} |
---|
128 | \pdfbookmark[1]{Contents}{section} |
---|
129 | \tableofcontents |
---|
130 | |
---|
131 | \clearpage |
---|
132 | \thispagestyle{plain} |
---|
133 | \pagenumbering{arabic} |
---|
134 | |
---|
135 | |
---|
136 | \section{Introduction} |
---|
137 | |
---|
138 | \CFA{}\index{cforall@\CFA}\footnote{Pronounced ``\Index*{C-for-all}'', and written \CFA, CFA, or \CFL.} is a modern general-purpose programming-language, designed as an evolutionary step forward for the C programming language. |
---|
139 | The syntax of the \CFA language builds from C, and should look immediately familiar to C/\Index*[C++]{\CC{}} programmers. |
---|
140 | % Any language feature that is not described here can be assumed to be using the standard \Celeven syntax. |
---|
141 | \CFA adds many modern programming-language features that directly lead to increased \emph{\Index{safety}} and \emph{\Index{productivity}}, while maintaining interoperability with existing C programs and achieving C performance. |
---|
142 | Like C, \CFA is a statically typed, procedural language with a low-overhead runtime, meaning there is no global \Index{garbage-collection}, but \Index{regional garbage-collection}\index{garbage-collection!regional} is possible. |
---|
143 | The primary new features include parametric-polymorphic routines and types, exceptions, concurrency, and modules. |
---|
144 | |
---|
145 | One 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''. |
---|
146 | Programmers 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. |
---|
147 | A 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. |
---|
148 | There is no notion or requirement for rewriting a legacy C program in \CFA; |
---|
149 | instead, a programmer evolves an existing C program into \CFA by incrementally incorporating \CFA features. |
---|
150 | New programs can be written in \CFA using a combination of C and \CFA features. |
---|
151 | \Index*[C++]{\CC{}} had a similar goal 30 years ago, but currently has the disadvantages of multiple legacy design-choices that cannot be updated and active divergence of the language model from C, requiring significant effort and training to incrementally add \CC to a C-based project. |
---|
152 | In contrast, \CFA has 30 years of hindsight and a clean starting point. |
---|
153 | |
---|
154 | Like \Index*[C++]{\CC{}}, there may be both an old and new ways to achieve the same effect. |
---|
155 | For example, the following programs compare the \CFA, C, and \CC I/O mechanisms, where the programs output the same result. |
---|
156 | \begin{quote2} |
---|
157 | \begin{tabular}{@{}l@{\hspace{1.5em}}l@{\hspace{1.5em}}l@{}} |
---|
158 | \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} & \multicolumn{1}{c}{\textbf{\CC}} \\ |
---|
159 | \begin{cfa} |
---|
160 | #include <fstream>§\indexc{fstream}§ |
---|
161 | |
---|
162 | int main( void ) { |
---|
163 | int x = 0, y = 1, z = 2; |
---|
164 | ®sout | x | y | z | endl;® |
---|
165 | } |
---|
166 | \end{cfa} |
---|
167 | & |
---|
168 | \begin{lstlisting} |
---|
169 | #include <stdio.h>§\indexc{stdio.h}§ |
---|
170 | |
---|
171 | int main( void ) { |
---|
172 | int x = 0, y = 1, z = 2; |
---|
173 | ®printf( "%d %d %d\n", x, y, z );® |
---|
174 | } |
---|
175 | \end{lstlisting} |
---|
176 | & |
---|
177 | \begin{lstlisting} |
---|
178 | #include <iostream>§\indexc{iostream}§ |
---|
179 | using namespace std; |
---|
180 | int main() { |
---|
181 | int x = 0, y = 1, z = 2; |
---|
182 | ®cout<<x<<" "<<y<<" "<<z<<endl;® |
---|
183 | } |
---|
184 | \end{lstlisting} |
---|
185 | \end{tabular} |
---|
186 | \end{quote2} |
---|
187 | While the \CFA I/O looks similar to the \Index*[C++]{\CC{}} output style, there are important differences, such as automatic spacing between variables as in \Index*{Python} (see~\VRef{s:IOLibrary}). |
---|
188 | |
---|
189 | This document is a programmer reference-manual for the \CFA programming language. |
---|
190 | The manual covers the core features of the language and runtime-system, with simple examples illustrating syntax and semantics of each feature. |
---|
191 | The manual does not teach programming, i.e., how to combine the new constructs to build complex programs. |
---|
192 | A reader should already have an intermediate knowledge of control flow, data structures, and concurrency issues to understand the ideas presented as well as some experience programming in C/\CC. |
---|
193 | Implementers may refer to the \CFA Programming Language Specification for details about the language syntax and semantics. |
---|
194 | Changes to the syntax and additional features are expected to be included in later revisions. |
---|
195 | |
---|
196 | |
---|
197 | \section{Why fix C?} |
---|
198 | |
---|
199 | The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from commercial operating-systems (especially UNIX systems) to hobby projects. |
---|
200 | This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more. |
---|
201 | Even with all its problems, C continues to be popular because it allows writing software at virtually any level in a computer system without restriction. |
---|
202 | For system programming, where direct access to hardware and dealing with real-time issues is a requirement, C is usually the language of choice. |
---|
203 | The TIOBE index~\cite{TIOBE} for March 2016 showed the following programming-language popularity: \Index*{Java} 20.5\%, C 14.5\%, \Index*[C++]{\CC{}} 6.7\%, \Csharp 4.3\%, \Index*{Python} 4.3\%, where the next 50 languages are less than 3\% each with a long tail. |
---|
204 | As well, for 30 years, C has been the number 1 and 2 most popular programming language: |
---|
205 | \begin{center} |
---|
206 | \setlength{\tabcolsep}{1.5ex} |
---|
207 | \begin{tabular}{@{}r|c|c|c|c|c|c|c@{}} |
---|
208 | Ranking & 2016 & 2011 & 2006 & 2001 & 1996 & 1991 & 1986 \\ |
---|
209 | \hline |
---|
210 | Java & 1 & 1 & 1 & 3 & 29 & - & - \\ |
---|
211 | \hline |
---|
212 | \R{C} & \R{2} & \R{2} & \R{2} & \R{1} & \R{1} & \R{1} & \R{1} \\ |
---|
213 | \hline |
---|
214 | \CC & 3 & 3 & 3 & 2 & 2 & 2 & 7 \\ |
---|
215 | \end{tabular} |
---|
216 | \end{center} |
---|
217 | Hence, C is still an extremely important programming language, with double the usage of \Index*[C++]{\CC{}}; in many cases, \CC is often used solely as a better C. |
---|
218 | Love it or hate it, C has been an important and influential part of computer science for 40 years and sit appeal is not diminishing. |
---|
219 | Unfortunately, C has too many problems and omissions to make it an acceptable programming language for modern needs. |
---|
220 | |
---|
221 | As stated, the goal of the \CFA project is to engineer modern language features into C in an evolutionary rather than revolutionary way. |
---|
222 | \CC~\cite{C++14,C++} is an example of a similar project; |
---|
223 | however, it largely extended the language, and did not address many existing problems.\footnote{% |
---|
224 | Two 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.} |
---|
225 | \Index*{Fortran}~\cite{Fortran08}, \Index*{Ada}~\cite{Ada12}, and \Index*{Cobol}~\cite{Cobol14} are examples of programming languages that took an evolutionary approach, where modern language features (\eg objects, concurrency) are added and problems fixed within the framework of the existing language. |
---|
226 | \Index*{Java}~\cite{Java8}, \Index*{Go}~\cite{Go}, \Index*{Rust}~\cite{Rust} and \Index*{D}~\cite{D} are examples of the revolutionary approach for modernizing C/\CC, resulting in a new language rather than an extension of the descendent. |
---|
227 | These languages have different syntax and semantics from C, and do not interoperate directly with C, largely because of garbage collection. |
---|
228 | As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten. |
---|
229 | These 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. |
---|
230 | |
---|
231 | The result of this project is a language that is largely backwards compatible with \Index*[C11]{\Celeven{}}~\cite{C11}, but fixing some of the well known C problems and containing many modern language features. |
---|
232 | Without significant extension to the C programming language, it is becoming unable to cope with the needs of modern programming problems and programmers; |
---|
233 | as a result, it will fade into disuse. |
---|
234 | Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language. |
---|
235 | While \Index*[C11]{\Celeven{}} 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. |
---|
236 | While 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. |
---|
237 | |
---|
238 | |
---|
239 | \section{History} |
---|
240 | |
---|
241 | The \CFA project started with \Index*{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. |
---|
242 | (See~\cite{Werther96} for similar work in \Index*[C++]{\CC{}}.) |
---|
243 | A first \CFA implementation of these extensions was by Esteves~\cite{Esteves04}. |
---|
244 | The signature feature of \CFA is parametric-polymorphic functions~\cite{forceone:impl,Cormack90,Duggan96} with functions generalized using a ©forall© clause (giving the language its name): |
---|
245 | \begin{lstlisting} |
---|
246 | ®forall( otype T )® T identity( T val ) { return val; } |
---|
247 | int forty_two = identity( 42 ); §\C{// T is bound to int, forty\_two == 42}§ |
---|
248 | \end{lstlisting} |
---|
249 | % extending the C type system with parametric polymorphism and overloading, as opposed to the \Index*[C++]{\CC{}} approach of object-oriented extensions. |
---|
250 | \CFA{}\hspace{1pt}'s polymorphism was originally formalized by Ditchfiled~\cite{Ditchfield92}, and first implemented by Bilson~\cite{Bilson03}. |
---|
251 | However, at that time, there was little interesting in extending C, so work did not continue. |
---|
252 | As 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. |
---|
253 | |
---|
254 | |
---|
255 | \section{Interoperability} |
---|
256 | \label{s:Interoperability} |
---|
257 | |
---|
258 | \CFA is designed to integrate directly with existing C programs and libraries. |
---|
259 | The most important feature of \Index{interoperability} is using the same \Index{calling convention}s, so there is no overhead to call existing C routines. |
---|
260 | This feature allows \CFA programmers to take advantage of the existing panoply of C libraries to access thousands of external software features. |
---|
261 | Language developers often state that adequate \Index{library support} takes more work than designing and implementing the language itself. |
---|
262 | Fortunately, \CFA, like \Index*[C++]{\CC{}}, 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. |
---|
263 | Hence, \CFA begins by leveraging the large repository of C libraries with little cost. |
---|
264 | |
---|
265 | \begin{comment} |
---|
266 | A simple example is leveraging the existing type-unsafe (©void *©) C ©bsearch© to binary search a sorted floating-point array: |
---|
267 | \begin{lstlisting} |
---|
268 | void * bsearch( const void * key, const void * base, size_t dim, size_t size, |
---|
269 | int (* compar)( const void *, const void * )); |
---|
270 | |
---|
271 | int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 : |
---|
272 | *(double *)t2 < *(double *)t1 ? 1 : 0; } |
---|
273 | |
---|
274 | double key = 5.0, vals[10] = { /* 10 sorted floating-point values */ }; |
---|
275 | double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp ); $\C{// search sorted array}$ |
---|
276 | \end{lstlisting} |
---|
277 | which can be augmented simply with a polymorphic, type-safe, \CFA-overloaded wrappers: |
---|
278 | \begin{lstlisting} |
---|
279 | forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) { |
---|
280 | int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ } |
---|
281 | return (T *)bsearch( &key, arr, size, sizeof(T), comp ); } |
---|
282 | |
---|
283 | forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) { |
---|
284 | T * result = bsearch( key, arr, size ); $\C{// call first version}$ |
---|
285 | return result ? result - arr : size; } $\C{// pointer subtraction includes sizeof(T)}$ |
---|
286 | |
---|
287 | double * val = bsearch( 5.0, vals, 10 ); $\C{// selection based on return type}$ |
---|
288 | int posn = bsearch( 5.0, vals, 10 ); |
---|
289 | \end{lstlisting} |
---|
290 | The nested function ©comp© provides the hidden interface from typed \CFA to untyped (©void *©) C, plus the cast of the result. |
---|
291 | Providing a hidden ©comp© function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope. |
---|
292 | As well, an alternate kind of return is made available: position versus pointer to found element. |
---|
293 | \CC's type-system cannot disambiguate between the two versions of ©bsearch© because it does not use the return type in overload resolution, nor can \CC separately compile a templated ©bsearch©. |
---|
294 | |
---|
295 | \CFA has replacement libraries condensing hundreds of existing C functions into tens of \CFA overloaded functions, all without rewriting the actual computations. |
---|
296 | For example, it is possible to write a type-safe \CFA wrapper ©malloc© based on the C ©malloc©: |
---|
297 | \begin{lstlisting} |
---|
298 | forall( dtype T | sized(T) ) T * malloc( void ) { return (T *)malloc( sizeof(T) ); } |
---|
299 | int * ip = malloc(); §\C{// select type and size from left-hand side}§ |
---|
300 | double * dp = malloc(); |
---|
301 | struct S {...} * sp = malloc(); |
---|
302 | \end{lstlisting} |
---|
303 | where the return type supplies the type/size of the allocation, which is impossible in most type systems. |
---|
304 | \end{comment} |
---|
305 | |
---|
306 | However, it is necessary to differentiate between C and \CFA code because of name overloading, as for \CC. |
---|
307 | For 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©. |
---|
308 | Whereas, \CFA wraps each of these routines into ones with the common name ©abs©: |
---|
309 | \begin{cfa} |
---|
310 | char abs( char ); |
---|
311 | ®extern "C" {® |
---|
312 | int abs( int ); §\C{// use default C routine for int}§ |
---|
313 | ®}® // extern "C" |
---|
314 | long int abs( long int ); |
---|
315 | long long int abs( long long int ); |
---|
316 | float abs( float ); |
---|
317 | double abs( double ); |
---|
318 | long double abs( long double ); |
---|
319 | float _Complex abs( float _Complex ); |
---|
320 | double _Complex abs( double _Complex ); |
---|
321 | long double _Complex abs( long double _Complex ); |
---|
322 | \end{cfa} |
---|
323 | The problem is the name clash between the library routine ©abs© and the \CFA names ©abs©. |
---|
324 | Hence, names appearing in an ©extern "C"© block have \newterm*{C linkage}. |
---|
325 | Then overloading polymorphism uses a mechanism called \newterm{name mangling}\index{mangling!name} to create unique names that are different from C names, which are not mangled. |
---|
326 | Hence, 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. |
---|
327 | There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type. |
---|
328 | This example strongly illustrates a core idea in \CFA: \emph{the power of a name}. |
---|
329 | The name ``©abs©'' evokes the notion of absolute value, and many mathematical types provide the notion of absolute value. |
---|
330 | Hence, knowing the name ©abs© should be sufficient to apply it to any type where it is applicable. |
---|
331 | The time savings and safety of using one name uniformly versus $N$ unique names should not be underestimated. |
---|
332 | |
---|
333 | |
---|
334 | \section[Compiling CFA Program]{Compiling \CFA Program} |
---|
335 | |
---|
336 | The command ©cfa© is used to compile \CFA program(s), and is based on the GNU \Indexc{gcc} command, \eg: |
---|
337 | \begin{cfa} |
---|
338 | cfa§\indexc{cfa}\index{compilation!cfa@©cfa©}§ [ gcc-options ] C/§\CFA§-files [ assembler/loader-files ] |
---|
339 | \end{cfa} |
---|
340 | \CFA programs having the following ©gcc© flags turned on: |
---|
341 | \begin{description} |
---|
342 | \item |
---|
343 | \Indexc{-std=gnu99}\index{compilation option!-std=gnu99@{©-std=gnu99©}} |
---|
344 | The 1999 C standard plus GNU extensions. |
---|
345 | \item |
---|
346 | {\lstset{deletekeywords={inline}} |
---|
347 | \Indexc{-fgnu89-inline}\index{compilation option!-fgnu89-inline@{©-fgnu89-inline©}} |
---|
348 | Use the traditional GNU semantics for inline routines in C99 mode, which allows inline routines in header files. |
---|
349 | }% |
---|
350 | \end{description} |
---|
351 | The following new \CFA options are available: |
---|
352 | \begin{description} |
---|
353 | \item |
---|
354 | \Indexc{-CFA}\index{compilation option!-CFA@©-CFA©} |
---|
355 | Only 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. |
---|
356 | The generated code started with the standard \CFA prelude. |
---|
357 | |
---|
358 | \item |
---|
359 | \Indexc{-debug}\index{compilation option!-debug@©-debug©} |
---|
360 | The program is linked with the debugging version of the runtime system. |
---|
361 | The debug version performs runtime checks to help during the debugging phase of a \CFA program, but substantially slows the execution of the program. |
---|
362 | The runtime checks should only be removed after the program is completely debugged. |
---|
363 | \textbf{This option is the default.} |
---|
364 | |
---|
365 | \item |
---|
366 | \Indexc{-nodebug}\index{compilation option!-nodebug@©-nodebug©} |
---|
367 | The program is linked with the non-debugging version of the runtime system, so the execution of the program is faster. |
---|
368 | \Emph{However, no runtime checks or ©assert©s are performed so errors usually result in abnormal program termination.} |
---|
369 | |
---|
370 | \item |
---|
371 | \Indexc{-help}\index{compilation option!-help@©-help©} |
---|
372 | Information about the set of \CFA compilation flags is printed. |
---|
373 | |
---|
374 | \item |
---|
375 | \Indexc{-nohelp}\index{compilation option!-nohelp@©-nohelp©} |
---|
376 | Information about the set of \CFA compilation flags is not printed. |
---|
377 | \textbf{This option is the default.} |
---|
378 | |
---|
379 | \item |
---|
380 | \Indexc{-quiet}\index{compilation option!-quiet@©-quiet©} |
---|
381 | The \CFA compilation message is not printed at the beginning of a compilation. |
---|
382 | |
---|
383 | \item |
---|
384 | \Indexc{-noquiet}\index{compilation option!-noquiet@©-noquiet©} |
---|
385 | The \CFA compilation message is printed at the beginning of a compilation. |
---|
386 | \textbf{This option is the default.} |
---|
387 | |
---|
388 | \item |
---|
389 | \Indexc{-no-include-stdhdr}\index{compilation option!-no-include-stdhdr@©-no-include-stdhdr©} |
---|
390 | Do not supply ©extern "C"© wrappers for \Celeven standard include files (see~\VRef{s:StandardHeaders}). |
---|
391 | \textbf{This option is \emph{not} the default.} |
---|
392 | \end{description} |
---|
393 | |
---|
394 | The following preprocessor variables are available: |
---|
395 | \begin{description} |
---|
396 | \item |
---|
397 | \Indexc{__CFA_MAJOR__}\index{preprocessor variables!__CFA__@{©__CFA__©}} |
---|
398 | is available during preprocessing and its value is the major \Index{version number} of \CFA.\footnote{ |
---|
399 | The C preprocessor allows only integer values in a preprocessor variable so a value like ``\Version'' is not allowed. |
---|
400 | Hence, the need to have three variables for the major, minor and patch version number.} |
---|
401 | |
---|
402 | \item |
---|
403 | \Indexc{__CFA_MINOR__}\index{preprocessor variables!__CFA_MINOR__@{©__CFA_MINOR__©}} |
---|
404 | is available during preprocessing and its value is the minor \Index{version number} of \CFA. |
---|
405 | |
---|
406 | \item |
---|
407 | \Indexc{__CFA_PATCH__}\index{preprocessor variables!__CFA_PATCH__@©__CFA_PATCH__©} |
---|
408 | is available during preprocessing and its value is the patch \Index{level number} of \CFA. |
---|
409 | |
---|
410 | \item |
---|
411 | \Indexc{__CFA__}\index{preprocessor variables!__CFA__@©__CFA__©}, |
---|
412 | \Indexc{__CFORALL__}\index{preprocessor variables!__CFORALL__@©__CFORALL__©} and |
---|
413 | \Indexc{__cforall}\index{preprocessor variables!__cforall@©__cforall©} |
---|
414 | are always available during preprocessing and have no value. |
---|
415 | \end{description} |
---|
416 | These preprocessor variables allow conditional compilation of programs that must work differently in these situations. |
---|
417 | For example, to toggle between C and \CFA extensions, using the following: |
---|
418 | \begin{cfa} |
---|
419 | #ifndef __CFORALL__ |
---|
420 | #include <stdio.h>§\indexc{stdio.h}§ §\C{// C header file}§ |
---|
421 | #else |
---|
422 | #include <fstream>§\indexc{fstream}§ §\C{// \CFA header file}§ |
---|
423 | #endif |
---|
424 | \end{cfa} |
---|
425 | which conditionally includes the correct header file, if the program is compiled using \Indexc{gcc} or \Indexc{cfa}. |
---|
426 | |
---|
427 | |
---|
428 | \section{Constants Underscores} |
---|
429 | |
---|
430 | Numeric constants are extended to allow \Index{underscore}s within constants\index{constant!underscore}, \eg: |
---|
431 | \begin{cfa} |
---|
432 | 2®_®147®_®483®_®648; §\C{// decimal constant}§ |
---|
433 | 56®_®ul; §\C{// decimal unsigned long constant}§ |
---|
434 | 0®_®377; §\C{// octal constant}§ |
---|
435 | 0x®_®ff®_®ff; §\C{// hexadecimal constant}§ |
---|
436 | 0x®_®ef3d®_®aa5c; §\C{// hexadecimal constant}§ |
---|
437 | 3.141®_®592®_®654; §\C{// floating point constant}§ |
---|
438 | 10®_®e®_®+1®_®00; §\C{// floating point constant}§ |
---|
439 | 0x®_®ff®_®ff®_®p®_®3; §\C{// hexadecimal floating point}§ |
---|
440 | 0x®_®1.ffff®_®ffff®_®p®_®128®_®l; §\C{// hexadecimal floating point long constant}§ |
---|
441 | L®_®§"\texttt{\textbackslash{x}}§®_®§\texttt{ff}§®_®§\texttt{ee}"§; §\C{// wide character constant}§ |
---|
442 | \end{cfa} |
---|
443 | The rules for placement of underscores is as follows: |
---|
444 | \begin{enumerate} |
---|
445 | \item |
---|
446 | A sequence of underscores is disallowed, \eg ©12__34© is invalid. |
---|
447 | \item |
---|
448 | Underscores may only appear within a sequence of digits (regardless of the digit radix). |
---|
449 | In other words, an underscore cannot start or end a sequence of digits, \eg ©_1©, ©1_© and ©_1_© are invalid (actually, the 1st and 3rd examples are identifier names). |
---|
450 | \item |
---|
451 | A numeric prefix may end with an underscore; |
---|
452 | a numeric infix may begin and/or end with an underscore; |
---|
453 | a numeric suffix may begin with an underscore. |
---|
454 | For example, the octal ©0© or hexadecimal ©0x© prefix may end with an underscore ©0_377© or ©0x_ff©; |
---|
455 | the exponent infix ©E© may start or end with an underscore ©1.0_E10©, ©1.0E_10© or ©1.0_E_10©; |
---|
456 | the type suffixes ©U©, ©L©, etc. may start with an underscore ©1_U©, ©1_ll© or ©1.0E10_f©. |
---|
457 | \end{enumerate} |
---|
458 | It is significantly easier to read and enter long constants when they are broken up into smaller groupings (many cultures use comma and/or period among digits for the same purpose). |
---|
459 | This extension is backwards compatible, matches with the use of underscore in variable names, and appears in \Index*{Ada} and \Index*{Java} 8. |
---|
460 | |
---|
461 | |
---|
462 | \section{Backquote Identifiers} |
---|
463 | \label{s:BackquoteIdentifiers} |
---|
464 | |
---|
465 | \CFA accommodates keyword clashes with existing C variable-names by syntactic transformations using the \CFA backquote escape-mechanism: |
---|
466 | \begin{cfa} |
---|
467 | int ®`®otype®`® = 3; §\C{// make keyword an identifier}§ |
---|
468 | double ®`®forall®`® = 3.5; |
---|
469 | \end{cfa} |
---|
470 | Existing C programs with keyword clashes can be converted by enclosing keyword identifiers in backquotes, and eventually the identifier name can be changed to a non-keyword name. |
---|
471 | \VRef[Figure]{f:InterpositionHeaderFile} shows how clashes in C header files (see~\VRef{s:StandardHeaders}) can be handled using preprocessor \newterm{interposition}: ©#include_next© and ©-I filename©: |
---|
472 | |
---|
473 | \begin{figure} |
---|
474 | \begin{cfa} |
---|
475 | // include file uses the CFA keyword "otype". |
---|
476 | #if ! defined( otype ) §\C{// nesting ?}§ |
---|
477 | #define otype ®`®otype®`® §\C{// make keyword an identifier}§ |
---|
478 | #define __CFA_BFD_H__ |
---|
479 | #endif // ! otype |
---|
480 | |
---|
481 | #®include_next® <bfd.h> §\C{// must have internal check for multiple expansion}§ |
---|
482 | |
---|
483 | #if defined( otype ) && defined( __CFA_BFD_H__ ) §\C{// reset only if set}§ |
---|
484 | #undef otype |
---|
485 | #undef __CFA_BFD_H__ |
---|
486 | #endif // otype && __CFA_BFD_H__ |
---|
487 | \end{cfa} |
---|
488 | \caption{Interposition of Header File} |
---|
489 | \label{f:InterpositionHeaderFile} |
---|
490 | \end{figure} |
---|
491 | |
---|
492 | |
---|
493 | \section{Labelled Continue/Break} |
---|
494 | |
---|
495 | While C provides ©continue© and ©break© statements for altering control flow, both are restricted to one level of nesting for a particular control structure. |
---|
496 | Unfortunately, this restriction forces programmers to use \Indexc{goto} to achieve the equivalent control-flow for more than one level of nesting. |
---|
497 | To prevent having to switch to the ©goto©, \CFA extends the \Indexc{continue}\index{continue@\lstinline $continue$!labelled}\index{labelled!continue@©continue©} and \Indexc{break}\index{break@\lstinline $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}. |
---|
498 | For both ©continue© and ©break©, the target label must be directly associated with a ©for©, ©while© or ©do© statement; |
---|
499 | for ©break©, the target label can also be associated with a ©switch©, ©if© or compound (©{}©) statement. |
---|
500 | \VRef[Figure]{f:MultiLevelResumeTermination} shows the labelled ©continue© and ©break©, specifying which control structure is the target for exit, and the corresponding C program using only ©goto©. |
---|
501 | The innermost loop has 7 exit points, which cause resumption or termination of one or more of the 7 \Index{nested control-structure}s. |
---|
502 | |
---|
503 | \begin{figure} |
---|
504 | \begin{tabular}{@{\hspace{\parindentlnth}}l@{\hspace{1.5em}}l@{}} |
---|
505 | \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
506 | \begin{cfa} |
---|
507 | ®LC:® { |
---|
508 | ... §declarations§ ... |
---|
509 | ®LS:® switch ( ... ) { |
---|
510 | case 3: |
---|
511 | ®LIF:® if ( ... ) { |
---|
512 | ®LF:® for ( ... ) { |
---|
513 | ®LW:® while ( ... ) { |
---|
514 | ... break ®LC®; ... // terminate compound |
---|
515 | ... break ®LS®; ... // terminate switch |
---|
516 | ... break ®LIF®; ... // terminate if |
---|
517 | ... continue ®LF;® ... // resume loop |
---|
518 | ... break ®LF®; ... // terminate loop |
---|
519 | ... continue ®LW®; ... // resume loop |
---|
520 | ... break ®LW®; ... // terminate loop |
---|
521 | } // while |
---|
522 | } // for |
---|
523 | } else { |
---|
524 | ... break ®LIF®; ... // terminate if |
---|
525 | } // if |
---|
526 | } // switch |
---|
527 | } // compound |
---|
528 | \end{cfa} |
---|
529 | & |
---|
530 | \begin{cfa} |
---|
531 | { |
---|
532 | ... §declarations§ ... |
---|
533 | switch ( ... ) { |
---|
534 | case 3: |
---|
535 | if ( ... ) { |
---|
536 | for ( ... ) { |
---|
537 | while ( ... ) { |
---|
538 | ... goto ®LC®; ... |
---|
539 | ... goto ®LS®; ... |
---|
540 | ... goto ®LIF®; ... |
---|
541 | ... goto ®LFC®; ... |
---|
542 | ... goto ®LFB®; ... |
---|
543 | ... goto ®LWC®; ... |
---|
544 | ... goto ®LWB®; ... |
---|
545 | ®LWC®: ; } ®LWB:® ; |
---|
546 | ®LFC:® ; } ®LFB:® ; |
---|
547 | } else { |
---|
548 | ... goto ®LIF®; ... |
---|
549 | } ®L3:® ; |
---|
550 | } ®LS:® ; |
---|
551 | } ®LC:® ; |
---|
552 | \end{cfa} |
---|
553 | \end{tabular} |
---|
554 | \caption{Multi-level Resume/Termination} |
---|
555 | \label{f:MultiLevelResumeTermination} |
---|
556 | \end{figure} |
---|
557 | |
---|
558 | \begin{comment} |
---|
559 | int main() { |
---|
560 | LC: { |
---|
561 | LS: switch ( 1 ) { |
---|
562 | case 3: |
---|
563 | LIF: if ( 1 ) { |
---|
564 | LF: for ( ;; ) { |
---|
565 | LW: while ( 1 ) { |
---|
566 | break LC; // terminate compound |
---|
567 | break LS; // terminate switch |
---|
568 | break LIF; // terminate if |
---|
569 | continue LF; // resume loop |
---|
570 | break LF; // terminate loop |
---|
571 | continue LW; // resume loop |
---|
572 | break LW; // terminate loop |
---|
573 | } // while |
---|
574 | } // for |
---|
575 | } else { |
---|
576 | break LIF; // terminate if |
---|
577 | } // if |
---|
578 | } // switch |
---|
579 | } // compound |
---|
580 | { |
---|
581 | switch ( 1 ) { |
---|
582 | case 3: |
---|
583 | if ( 1 ) { |
---|
584 | for ( ;; ) { |
---|
585 | while ( 1 ) { |
---|
586 | goto LCx; |
---|
587 | goto LSx; |
---|
588 | goto LIF; |
---|
589 | goto LFC; |
---|
590 | goto LFB; |
---|
591 | goto LWC; |
---|
592 | goto LWB; |
---|
593 | LWC: ; } LWB: ; |
---|
594 | LFC: ; } LFB: ; |
---|
595 | } else { |
---|
596 | goto LIF; |
---|
597 | } L3: ; |
---|
598 | } LSx: ; |
---|
599 | } LCx: ; |
---|
600 | } |
---|
601 | |
---|
602 | // Local Variables: // |
---|
603 | // tab-width: 4 // |
---|
604 | // End: // |
---|
605 | \end{comment} |
---|
606 | |
---|
607 | |
---|
608 | Both labelled ©continue© and ©break© are a ©goto©\index{goto@\lstinline $goto$!restricted} restricted in the following ways: |
---|
609 | \begin{itemize} |
---|
610 | \item |
---|
611 | They cannot create a loop, which means only the looping constructs cause looping. |
---|
612 | This restriction means all situations resulting in repeated execution are clearly delineated. |
---|
613 | \item |
---|
614 | They cannot branch into a control structure. |
---|
615 | This restriction prevents missing initialization at the start of a control structure resulting in undefined behaviour. |
---|
616 | \end{itemize} |
---|
617 | The 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. |
---|
618 | Furthermore, 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. |
---|
619 | With ©goto©, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader. |
---|
620 | Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs. |
---|
621 | The implicit targets of the current ©continue© and ©break©, \ie the closest enclosing loop or ©switch©, change as certain constructs are added or removed. |
---|
622 | |
---|
623 | |
---|
624 | \section{Switch Statement} |
---|
625 | |
---|
626 | C allows a number of questionable forms for the ©switch© statement: |
---|
627 | \begin{enumerate} |
---|
628 | \item |
---|
629 | By default, the end of a ©case© clause\footnote{ |
---|
630 | In this section, the term \emph{case clause} refers to either a ©case© or ©default© clause.} |
---|
631 | \emph{falls through} to the next ©case© clause in the ©switch© statement; |
---|
632 | to exit a ©switch© statement from a ©case© clause requires explicitly terminating the clause with a transfer statement, most commonly ©break©: |
---|
633 | \begin{cfa} |
---|
634 | switch ( i ) { |
---|
635 | case 1: |
---|
636 | ... |
---|
637 | // fall-through |
---|
638 | case 2: |
---|
639 | ... |
---|
640 | break; // exit switch statement |
---|
641 | } |
---|
642 | \end{cfa} |
---|
643 | The ability to fall-through to the next clause \emph{is} a useful form of control flow, specifically when a sequence of case actions compound: |
---|
644 | \begin{quote2} |
---|
645 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
646 | \begin{cfa} |
---|
647 | switch ( argc ) { |
---|
648 | case 3: |
---|
649 | // open output file |
---|
650 | // fall-through |
---|
651 | case 2: |
---|
652 | // open input file |
---|
653 | break; // exit switch statement |
---|
654 | default: |
---|
655 | // usage message |
---|
656 | } |
---|
657 | \end{cfa} |
---|
658 | & |
---|
659 | \begin{cfa} |
---|
660 | |
---|
661 | if ( argc == 3 ) { |
---|
662 | // open output file |
---|
663 | ®// open input file |
---|
664 | ®} else if ( argc == 2 ) { |
---|
665 | ®// open input file |
---|
666 | |
---|
667 | ®} else { |
---|
668 | // usage message |
---|
669 | } |
---|
670 | \end{cfa} |
---|
671 | \end{tabular} |
---|
672 | \end{quote2} |
---|
673 | In this example, case 2 is always done if case 3 is done. |
---|
674 | This 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. |
---|
675 | C also uses fall-through to handle multiple case-values resulting in the same action: |
---|
676 | \begin{cfa} |
---|
677 | switch ( i ) { |
---|
678 | case 1: case 3: case 5: // odd values |
---|
679 | // same action |
---|
680 | break; |
---|
681 | case 2: case 4: case 6: // even values |
---|
682 | // same action |
---|
683 | break; |
---|
684 | } |
---|
685 | \end{cfa} |
---|
686 | However, this situation is handled in other languages without fall-through by allowing a list of case values. |
---|
687 | While fall-through itself is not a problem, the problem occurs when fall-through is the default, as this semantics is unintuitive to many programmers and is different from virtually all other programming languages with a ©switch© statement. |
---|
688 | Hence, 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. |
---|
689 | |
---|
690 | \item |
---|
691 | It is possible to place ©case© clauses on statements nested \emph{within} the body of the ©switch© statement: |
---|
692 | \begin{cfa} |
---|
693 | switch ( i ) { |
---|
694 | case 0: |
---|
695 | if ( j < k ) { |
---|
696 | ... |
---|
697 | ®case 1:® // transfer into "if" statement |
---|
698 | ... |
---|
699 | } // if |
---|
700 | case 2: |
---|
701 | while ( j < 5 ) { |
---|
702 | ... |
---|
703 | ®case 3:® // transfer into "while" statement |
---|
704 | ... |
---|
705 | } // while |
---|
706 | } // switch |
---|
707 | \end{cfa} |
---|
708 | The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties. |
---|
709 | The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it. |
---|
710 | The technical problem results from the inability to ensure allocation and initialization of variables when blocks are not entered at the beginning. |
---|
711 | Often transferring into a block can bypass variable declaration and/or its initialization, which results in subsequent errors. |
---|
712 | There are virtually no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it. |
---|
713 | Nevertheless, C does have an idiom where this capability is used, known as ``\Index*{Duff's device}''~\cite{Duff83}: |
---|
714 | \begin{cfa} |
---|
715 | register int n = (count + 7) / 8; |
---|
716 | switch ( count % 8 ) { |
---|
717 | case 0: do{ *to = *from++; |
---|
718 | case 7: *to = *from++; |
---|
719 | case 6: *to = *from++; |
---|
720 | case 5: *to = *from++; |
---|
721 | case 4: *to = *from++; |
---|
722 | case 3: *to = *from++; |
---|
723 | case 2: *to = *from++; |
---|
724 | case 1: *to = *from++; |
---|
725 | } while ( --n > 0 ); |
---|
726 | } |
---|
727 | \end{cfa} |
---|
728 | which unrolls a loop N times (N = 8 above) and uses the ©switch© statement to deal with any iterations not a multiple of N. |
---|
729 | While efficient, this sort of special purpose usage is questionable: |
---|
730 | \begin{quote} |
---|
731 | Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this |
---|
732 | discovery.~\cite{Duff83} |
---|
733 | \end{quote} |
---|
734 | \item |
---|
735 | It is possible to place the ©default© clause anywhere in the list of labelled clauses for a ©switch© statement, rather than only at the end. |
---|
736 | Virtually all programming languages with a ©switch© statement require the ©default© clause to appear last in the case-clause list. |
---|
737 | The logic for this semantics is that after checking all the ©case© clauses without success, the ©default© clause is selected; |
---|
738 | hence, physically placing the ©default© clause at the end of the ©case© clause list matches with this semantics. |
---|
739 | This physical placement can be compared to the physical placement of an ©else© clause at the end of a series of connected ©if©/©else© statements. |
---|
740 | |
---|
741 | \item |
---|
742 | It is possible to place unreachable code at the start of a ©switch© statement, as in: |
---|
743 | \begin{cfa} |
---|
744 | switch ( x ) { |
---|
745 | ®int y = 1;® §\C{// unreachable initialization}§ |
---|
746 | ®x = 7;® §\C{// unreachable code without label/branch}§ |
---|
747 | case 3: ... |
---|
748 | ... |
---|
749 | ®int z = 0;® §\C{// unreachable initialization, cannot appear after case}§ |
---|
750 | z = 2; |
---|
751 | case 3: |
---|
752 | ®x = z;® §\C{// without fall through, z is uninitialized}§ |
---|
753 | } |
---|
754 | \end{cfa} |
---|
755 | While the declaration of the local variable ©y© is useful with a scope across all ©case© clauses, the initialization for such a variable is defined to never be executed because control always transfers over it. |
---|
756 | Furthermore, any statements before the first ©case© clause can only be executed if labelled and transferred to using a ©goto©, either from outside or inside of the ©switch©, both of which are problematic. |
---|
757 | As well, the declaration of ©z© cannot occur after the ©case© because a label can only be attached to a statement, and without a fall through to case 3, ©z© is uninitialized. |
---|
758 | The key observation is that the ©switch© statement branches into control structure, \ie there are multiple entry points into its statement body. |
---|
759 | \end{enumerate} |
---|
760 | |
---|
761 | Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program: |
---|
762 | \begin{itemize} |
---|
763 | \item |
---|
764 | the number of ©switch© statements is small, |
---|
765 | \item |
---|
766 | most ©switch© statements are well formed (\ie no \Index*{Duff's device}), |
---|
767 | \item |
---|
768 | the ©default© clause is usually written as the last case-clause, |
---|
769 | \item |
---|
770 | and 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. |
---|
771 | \end{itemize} |
---|
772 | These observations help to put the \CFA changes to the ©switch© into perspective. |
---|
773 | \begin{enumerate} |
---|
774 | \item |
---|
775 | Eliminating default fall-through has the greatest potential for affecting existing code. |
---|
776 | However, 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, \ie a list of ©case© clauses executing common code, \eg: |
---|
777 | \begin{cfa} |
---|
778 | case 1: case 2: case 3: ... |
---|
779 | \end{cfa} |
---|
780 | still works. |
---|
781 | Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments. |
---|
782 | Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called ©choose©, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword ©fallthrough©/©fallthru©, \eg: |
---|
783 | \begin{cfa} |
---|
784 | ®choose® ( i ) { |
---|
785 | case 1: case 2: case 3: |
---|
786 | ... |
---|
787 | ®// implicit end of switch (break) |
---|
788 | ®case 5: |
---|
789 | ... |
---|
790 | ®fallthru®; §\C{// explicit fall through}§ |
---|
791 | case 7: |
---|
792 | ... |
---|
793 | ®break® §\C{// explicit end of switch}§ |
---|
794 | default: |
---|
795 | j = 3; |
---|
796 | } |
---|
797 | \end{cfa} |
---|
798 | Like the ©switch© statement, the ©choose© statement retains the fall-through semantics for a list of ©case© clauses; |
---|
799 | the implicit ©break© is applied only at the end of the \emph{statements} following a ©case© clause. |
---|
800 | The explicit ©fallthru© is retained because it is a C-idiom most C programmers expect, and its absence might discourage programmers from using the ©choose© statement. |
---|
801 | As well, allowing an explicit ©break© from the ©choose© is a carry over from the ©switch© statement, and expected by C programmers. |
---|
802 | \item |
---|
803 | \Index*{Duff's device} is eliminated from both ©switch© and ©choose© statements, and only invalidates a small amount of very questionable code. |
---|
804 | Hence, the ©case© clause must appear at the same nesting level as the ©switch©/©choose© body, as is done in most other programming languages with ©switch© statements. |
---|
805 | \item |
---|
806 | The 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. |
---|
807 | Therefore, no change is made for this issue. |
---|
808 | \item |
---|
809 | Dealing with unreachable code in a ©switch©/©choose© body is solved by restricting declarations and associated initialization to the start of statement body, which is executed \emph{before} the transfer to the appropriate ©case© clause\footnote{ |
---|
810 | Essentially, these declarations are hoisted before the ©switch©/©choose© statement and both declarations and statement are surrounded by a compound statement.} and precluding statements before the first ©case© clause. |
---|
811 | Further declarations at the same nesting level as the statement body are disallowed to ensure every transfer into the body is sound. |
---|
812 | \begin{cfa} |
---|
813 | switch ( x ) { |
---|
814 | ®int i = 0;® §\C{// allowed only at start}§ |
---|
815 | case 0: |
---|
816 | ... |
---|
817 | ®int j = 0;® §\C{// disallowed}§ |
---|
818 | case 1: |
---|
819 | { |
---|
820 | ®int k = 0;® §\C{// allowed at different nesting levels}§ |
---|
821 | ... |
---|
822 | } |
---|
823 | ... |
---|
824 | } |
---|
825 | \end{cfa} |
---|
826 | \end{enumerate} |
---|
827 | |
---|
828 | |
---|
829 | \section{Case Clause} |
---|
830 | |
---|
831 | C restricts the ©case© clause of a ©switch© statement to a single value. |
---|
832 | For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values. |
---|
833 | Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C. |
---|
834 | Therefore, the ©case© clause is extended with a list of values, as in: |
---|
835 | \begin{quote2} |
---|
836 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
837 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
838 | \begin{cfa} |
---|
839 | switch ( i ) { |
---|
840 | case ®1, 3, 5®: |
---|
841 | ... |
---|
842 | case ®2, 4, 6®: |
---|
843 | ... |
---|
844 | } |
---|
845 | \end{cfa} |
---|
846 | & |
---|
847 | \begin{cfa} |
---|
848 | switch ( i ) { |
---|
849 | case 1: case 3 : case 5: |
---|
850 | ... |
---|
851 | case 2: case 4 : case 6: |
---|
852 | ... |
---|
853 | } |
---|
854 | \end{cfa} |
---|
855 | & |
---|
856 | \begin{cfa} |
---|
857 | |
---|
858 | // odd values |
---|
859 | |
---|
860 | // even values |
---|
861 | |
---|
862 | |
---|
863 | \end{cfa} |
---|
864 | \end{tabular} |
---|
865 | \end{quote2} |
---|
866 | In addition, two forms of subranges are allowed to specify case values: a new \CFA form and an existing GNU C form.\footnote{ |
---|
867 | The GNU C form \emph{requires} spaces around the ellipse.} |
---|
868 | \begin{quote2} |
---|
869 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
870 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{GNU C}} \\ |
---|
871 | \begin{cfa} |
---|
872 | switch ( i ) { |
---|
873 | case ®1~5:® |
---|
874 | ... |
---|
875 | case ®10~15:® |
---|
876 | ... |
---|
877 | } |
---|
878 | \end{cfa} |
---|
879 | & |
---|
880 | \begin{cfa} |
---|
881 | switch ( i ) |
---|
882 | case ®1 ... 5®: |
---|
883 | ... |
---|
884 | case ®10 ... 15®: |
---|
885 | ... |
---|
886 | } |
---|
887 | \end{cfa} |
---|
888 | & |
---|
889 | \begin{cfa} |
---|
890 | |
---|
891 | // 1, 2, 3, 4, 5 |
---|
892 | |
---|
893 | // 10, 11, 12, 13, 14, 15 |
---|
894 | |
---|
895 | |
---|
896 | \end{cfa} |
---|
897 | \end{tabular} |
---|
898 | \end{quote2} |
---|
899 | Lists of subranges are also allowed. |
---|
900 | \begin{cfa} |
---|
901 | case ®1~5, 12~21, 35~42®: |
---|
902 | \end{cfa} |
---|
903 | |
---|
904 | |
---|
905 | \section{Exception Handling} |
---|
906 | |
---|
907 | Exception handling provides two mechanism: change of control flow from a raise to a handler, and communication from the raise to the handler. |
---|
908 | \begin{cfa} |
---|
909 | exception void h( int i ); |
---|
910 | exception int h( int i, double d ); |
---|
911 | |
---|
912 | void f(...) { |
---|
913 | ... throw h( 3 ); |
---|
914 | ... i = resume h( 3, 5.1 ); |
---|
915 | } |
---|
916 | |
---|
917 | try { |
---|
918 | f(...); |
---|
919 | } catch h( int w ) { |
---|
920 | // reset |
---|
921 | } resume h( int p, double x ) { |
---|
922 | return 17; // recover |
---|
923 | } finally { |
---|
924 | } |
---|
925 | \end{cfa} |
---|
926 | So 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. |
---|
927 | The 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. |
---|
928 | |
---|
929 | |
---|
930 | \subsection{Exception Hierarchy} |
---|
931 | |
---|
932 | An exception type can be derived from another exception type, just like deriving a subclass from a class, providing a kind of polymorphism among exception types. |
---|
933 | The exception-type hierarchy that is created is used to organize exception types, similar to a class hierarchy in object-oriented languages, \eg: |
---|
934 | \begin{center} |
---|
935 | \input{EHMHierarchy} |
---|
936 | \end{center} |
---|
937 | A programmer can then choose to handle an exception at different degrees of specificity along the hierarchy; |
---|
938 | derived exception-types support a more flexible programming style. |
---|
939 | For example, higher-level code should catch general exceptions to reduce coupling to the specific implementation at the lower levels; |
---|
940 | unnecessary coupling may force changes in higher-level code when low-level code changes. |
---|
941 | A consequence of derived exception-types is that multiple exceptions may match, \eg: |
---|
942 | \begin{cfa} |
---|
943 | catch( Arithmetic ) |
---|
944 | \end{cfa} |
---|
945 | matches all three derived exception-types: ©DivideByZero©, ©Overflow©, and ©Underflow©. |
---|
946 | Because the propagation mechanisms perform a simple linear search of the handler clause for a guarded block, and selects the first matching handler, the order of catch clauses in the handler clause becomes important, \eg: |
---|
947 | \begin{cfa} |
---|
948 | try { |
---|
949 | ... |
---|
950 | } catch( Overflow ) { // must appear first |
---|
951 | // handle overflow |
---|
952 | } catch( Arithmetic ) |
---|
953 | // handle other arithmetic issues |
---|
954 | } |
---|
955 | \end{cfa} |
---|
956 | \newterm{Multiple derivation} among exception is not supported. |
---|
957 | |
---|
958 | |
---|
959 | \section{Declarations} |
---|
960 | \label{s:Declarations} |
---|
961 | |
---|
962 | C declaration syntax is notoriously confusing and error prone. |
---|
963 | For example, many C programmers are confused by a declaration as simple as: |
---|
964 | \begin{quote2} |
---|
965 | \begin{tabular}{@{}ll@{}} |
---|
966 | \begin{cfa} |
---|
967 | int * x[5] |
---|
968 | \end{cfa} |
---|
969 | & |
---|
970 | \raisebox{-0.75\totalheight}{\input{Cdecl}} |
---|
971 | \end{tabular} |
---|
972 | \end{quote2} |
---|
973 | Is this an array of 5 pointers to integers or a \Index{pointer} to an array of 5 integers? |
---|
974 | The fact this declaration is unclear to many C programmers means there are \Index{productivity} and \Index{safety} issues even for basic programs. |
---|
975 | Another 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. |
---|
976 | For example, a routine returning a \Index{pointer} to an array of integers is defined and used in the following way: |
---|
977 | \begin{cfa} |
---|
978 | int ®(*®f®())[®5®]® {...}; §\C{definition}§ |
---|
979 | ... ®(*®f®())[®3®]® += 1; §\C{usage}§ |
---|
980 | \end{cfa} |
---|
981 | Essentially, the return type is wrapped around the routine name in successive layers (like an \Index{onion}). |
---|
982 | While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice. |
---|
983 | |
---|
984 | \CFA provides its own type, variable and routine declarations, using a different syntax. |
---|
985 | The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right of the base type. |
---|
986 | In the following example, \R{red} is the base type and \B{blue} is qualifiers. |
---|
987 | The \CFA declarations move the qualifiers to the left of the base type, \ie move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type. |
---|
988 | \begin{quote2} |
---|
989 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
990 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
991 | \begin{cfa} |
---|
992 | ß[5] *ß ®int® x1; |
---|
993 | ß* [5]ß ®int® x2; |
---|
994 | ß[* [5] int]ß f®( int p )®; |
---|
995 | \end{cfa} |
---|
996 | & |
---|
997 | \begin{cfa} |
---|
998 | ®int® ß*ß x1 ß[5]ß; |
---|
999 | ®int® ß(*ßx2ß)[5]ß; |
---|
1000 | ßint (*ßf®( int p )®ß)[5]ß; |
---|
1001 | \end{cfa} |
---|
1002 | \end{tabular} |
---|
1003 | \end{quote2} |
---|
1004 | The only exception is \Index{bit field} specification, which always appear to the right of the base type. |
---|
1005 | % 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. |
---|
1006 | However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list. |
---|
1007 | For instance, variables ©x© and ©y© of type \Index{pointer} to integer are defined in \CFA as follows: |
---|
1008 | \begin{quote2} |
---|
1009 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1010 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1011 | \begin{cfa} |
---|
1012 | ®*® int x, y; |
---|
1013 | \end{cfa} |
---|
1014 | & |
---|
1015 | \begin{cfa} |
---|
1016 | int ®*®x, ®*®y; |
---|
1017 | \end{cfa} |
---|
1018 | \end{tabular} |
---|
1019 | \end{quote2} |
---|
1020 | The downside of this semantics is the need to separate regular and \Index{pointer} declarations: |
---|
1021 | \begin{quote2} |
---|
1022 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1023 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1024 | \begin{cfa} |
---|
1025 | ®*® int x; |
---|
1026 | int y; |
---|
1027 | \end{cfa} |
---|
1028 | & |
---|
1029 | \begin{cfa} |
---|
1030 | int ®*®x, y; |
---|
1031 | |
---|
1032 | \end{cfa} |
---|
1033 | \end{tabular} |
---|
1034 | \end{quote2} |
---|
1035 | which is \Index{prescribing} a safety benefit. |
---|
1036 | Other examples are: |
---|
1037 | \begin{quote2} |
---|
1038 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
1039 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
1040 | \begin{cfa} |
---|
1041 | [ 5 ] int z; |
---|
1042 | [ 5 ] * char w; |
---|
1043 | * [ 5 ] double v; |
---|
1044 | struct s { |
---|
1045 | int f0:3; |
---|
1046 | * int f1; |
---|
1047 | [ 5 ] * int f2; |
---|
1048 | }; |
---|
1049 | \end{cfa} |
---|
1050 | & |
---|
1051 | \begin{cfa} |
---|
1052 | int z[ 5 ]; |
---|
1053 | char * w[ 5 ]; |
---|
1054 | double (* v)[ 5 ]; |
---|
1055 | struct s { |
---|
1056 | int f0:3; |
---|
1057 | int * f1; |
---|
1058 | int * f2[ 5 ] |
---|
1059 | }; |
---|
1060 | \end{cfa} |
---|
1061 | & |
---|
1062 | \begin{cfa} |
---|
1063 | // array of 5 integers |
---|
1064 | // array of 5 pointers to char |
---|
1065 | // pointer to array of 5 doubles |
---|
1066 | |
---|
1067 | // common bit field syntax |
---|
1068 | |
---|
1069 | |
---|
1070 | |
---|
1071 | \end{cfa} |
---|
1072 | \end{tabular} |
---|
1073 | \end{quote2} |
---|
1074 | |
---|
1075 | All type qualifiers, \eg ©const©, ©volatile©, etc., are used in the normal way with the new declarations and also appear left to right, \eg: |
---|
1076 | \begin{quote2} |
---|
1077 | \begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}} |
---|
1078 | \multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\ |
---|
1079 | \begin{cfa} |
---|
1080 | const * const int x; |
---|
1081 | const * [ 5 ] const int y; |
---|
1082 | \end{cfa} |
---|
1083 | & |
---|
1084 | \begin{cfa} |
---|
1085 | int const * const x; |
---|
1086 | const int (* const y)[ 5 ] |
---|
1087 | \end{cfa} |
---|
1088 | & |
---|
1089 | \begin{cfa} |
---|
1090 | // const pointer to const integer |
---|
1091 | // const pointer to array of 5 const integers |
---|
1092 | \end{cfa} |
---|
1093 | \end{tabular} |
---|
1094 | \end{quote2} |
---|
1095 | All declaration qualifiers, \eg ©extern©, ©static©, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier} |
---|
1096 | The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}} \eg: |
---|
1097 | \begin{quote2} |
---|
1098 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
1099 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
1100 | \begin{cfa} |
---|
1101 | extern [ 5 ] int x; |
---|
1102 | static * const int y; |
---|
1103 | \end{cfa} |
---|
1104 | & |
---|
1105 | \begin{cfa} |
---|
1106 | int extern x[ 5 ]; |
---|
1107 | const int static * y; |
---|
1108 | \end{cfa} |
---|
1109 | & |
---|
1110 | \begin{cfa} |
---|
1111 | // externally visible array of 5 integers |
---|
1112 | // internally visible pointer to constant int |
---|
1113 | \end{cfa} |
---|
1114 | \end{tabular} |
---|
1115 | \end{quote2} |
---|
1116 | |
---|
1117 | The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine ©sizeof©: |
---|
1118 | \begin{quote2} |
---|
1119 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1120 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1121 | \begin{cfa} |
---|
1122 | y = (®* int®)x; |
---|
1123 | i = sizeof(®[ 5 ] * int®); |
---|
1124 | \end{cfa} |
---|
1125 | & |
---|
1126 | \begin{cfa} |
---|
1127 | y = (®int *®)x; |
---|
1128 | i = sizeof(®int * [ 5 ]®); |
---|
1129 | \end{cfa} |
---|
1130 | \end{tabular} |
---|
1131 | \end{quote2} |
---|
1132 | |
---|
1133 | Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration. |
---|
1134 | Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style. |
---|
1135 | Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems. |
---|
1136 | |
---|
1137 | |
---|
1138 | \section{Pointer/Reference} |
---|
1139 | |
---|
1140 | C provides a \newterm{pointer type}; |
---|
1141 | \CFA adds a \newterm{reference type}. |
---|
1142 | These types may be derived from an object or routine type, called the \newterm{referenced type}. |
---|
1143 | Objects of these types contain an \newterm{address}, which is normally a location in memory, but may also address memory-mapped registers in hardware devices. |
---|
1144 | An integer constant expression with the value 0, or such an expression cast to type ©void *©, is called a \newterm{null-pointer constant}.\footnote{ |
---|
1145 | One way to conceptualize the null pointer is that no variable is placed at this address, so the null-pointer address can be used to denote an uninitialized pointer/reference object; |
---|
1146 | \ie the null pointer is guaranteed to compare unequal to a pointer to any object or routine.} |
---|
1147 | An address is \newterm{sound}, if it points to a valid memory location in scope, \ie within the program's execution-environment and has not been freed. |
---|
1148 | Dereferencing an \newterm{unsound} address, including the null pointer, is \Index{undefined}, often resulting in a \Index{memory fault}. |
---|
1149 | |
---|
1150 | A program \newterm{object} is a region of data storage in the execution environment, the contents of which can represent values. |
---|
1151 | In most cases, objects are located in memory at an address, and the variable name for an object is an implicit address to the object generated by the compiler and automatically dereferenced, as in: |
---|
1152 | \begin{quote2} |
---|
1153 | \begin{tabular}{@{}ll@{\hspace{2em}}l@{}} |
---|
1154 | \begin{cfa} |
---|
1155 | int x; |
---|
1156 | x = 3; |
---|
1157 | int y; |
---|
1158 | y = x; |
---|
1159 | \end{cfa} |
---|
1160 | & |
---|
1161 | \raisebox{-0.45\totalheight}{\input{pointer1}} |
---|
1162 | & |
---|
1163 | \begin{cfa} |
---|
1164 | int * ®const® x = (int *)100 |
---|
1165 | *x = 3; // implicit dereference |
---|
1166 | int * ®const® y = (int *)104; |
---|
1167 | *y = *x; // implicit dereference |
---|
1168 | \end{cfa} |
---|
1169 | \end{tabular} |
---|
1170 | \end{quote2} |
---|
1171 | where the right example is how the compiler logically interprets the variables in the left example. |
---|
1172 | Since a variable name only points to one address during its lifetime, it is an \Index{immutable} \Index{pointer}; |
---|
1173 | hence, the implicit type of pointer variables ©x© and ©y© are constant pointers in the compiler interpretation. |
---|
1174 | In general, variable addresses are stored in instructions instead of loaded from memory, and hence may not occupy storage. |
---|
1175 | These approaches are contrasted in the following: |
---|
1176 | \begin{quote2} |
---|
1177 | \begin{tabular}{@{}l|l@{}} |
---|
1178 | \multicolumn{1}{c|}{explicit variable address} & \multicolumn{1}{c}{implicit variable address} \\ |
---|
1179 | \hline |
---|
1180 | \begin{cfa} |
---|
1181 | lda r1,100 // load address of x |
---|
1182 | ld r2,(r1) // load value of x |
---|
1183 | lda r3,104 // load address of y |
---|
1184 | st r2,(r3) // store x into y |
---|
1185 | \end{cfa} |
---|
1186 | & |
---|
1187 | \begin{cfa} |
---|
1188 | |
---|
1189 | ld r2,(100) // load value of x |
---|
1190 | |
---|
1191 | st r2,(104) // store x into y |
---|
1192 | \end{cfa} |
---|
1193 | \end{tabular} |
---|
1194 | \end{quote2} |
---|
1195 | Finally, the immutable nature of a variable's address and the fact that there is no storage for the variable pointer means pointer assignment\index{pointer!assignment}\index{assignment!pointer} is impossible. |
---|
1196 | Therefore, the expression ©x = y© has only one meaning, ©*x = *y©, \ie manipulate values, which is why explicitly writing the dereferences is unnecessary even though it occurs implicitly as part of \Index{instruction decoding}. |
---|
1197 | |
---|
1198 | A \Index{pointer}/\Index{reference} object is a generalization of an object variable-name, \ie a mutable address that can point to more than one memory location during its lifetime. |
---|
1199 | (Similarly, an integer variable can contain multiple integer literals during its lifetime versus an integer constant representing a single literal during its lifetime, and like a variable name, may not occupy storage if the literal is embedded directly into instructions.) |
---|
1200 | Hence, a pointer occupies memory to store its current address, and the pointer's value is loaded by dereferencing, \eg: |
---|
1201 | \begin{quote2} |
---|
1202 | \begin{tabular}{@{}l@{\hspace{2em}}l@{}} |
---|
1203 | \begin{cfa} |
---|
1204 | int x, y, ®*® p1, ®*® p2, ®**® p3; |
---|
1205 | p1 = ®&®x; // p1 points to x |
---|
1206 | p2 = p1; // p2 points to x |
---|
1207 | p1 = ®&®y; // p1 points to y |
---|
1208 | p3 = &p2; // p3 points to p2 |
---|
1209 | \end{cfa} |
---|
1210 | & |
---|
1211 | \raisebox{-0.5\totalheight}{\input{pointer2.pstex_t}} |
---|
1212 | \end{tabular} |
---|
1213 | \end{quote2} |
---|
1214 | |
---|
1215 | Notice, an address has a \Index{duality}\index{address!duality}: a location in memory or the value at that location. |
---|
1216 | In many cases, a compiler might be able to infer the best meaning for these two cases. |
---|
1217 | For example, \Index*{Algol68}~\cite{Algol68} infers pointer dereferencing to select the best meaning for each pointer usage |
---|
1218 | \begin{cfa} |
---|
1219 | p2 = p1 + x; §\C{// compiler infers *p2 = *p1 + x;}§ |
---|
1220 | \end{cfa} |
---|
1221 | Algol68 infers the following dereferencing ©*p2 = *p1 + x©, because adding the arbitrary integer value in ©x© to the address of ©p1© and storing the resulting address into ©p2© is an unlikely operation. |
---|
1222 | Unfortunately, automatic dereferencing does not work in all cases, and so some mechanism is necessary to fix incorrect choices. |
---|
1223 | |
---|
1224 | Rather than inferring dereference, most programming languages pick one implicit dereferencing semantics, and the programmer explicitly indicates the other to resolve address-duality. |
---|
1225 | In C, objects of pointer type always manipulate the pointer object's address: |
---|
1226 | \begin{cfa} |
---|
1227 | p1 = p2; §\C{// p1 = p2\ \ rather than\ \ *p1 = *p2}§ |
---|
1228 | p2 = p1 + x; §\C{// p2 = p1 + x\ \ rather than\ \ *p2 = *p1 + x}§ |
---|
1229 | \end{cfa} |
---|
1230 | even though the assignment to ©p2© is likely incorrect, and the programmer probably meant: |
---|
1231 | \begin{cfa} |
---|
1232 | p1 = p2; §\C{// pointer address assignment}§ |
---|
1233 | ®*®p2 = ®*®p1 + x; §\C{// pointed-to value assignment / operation}§ |
---|
1234 | \end{cfa} |
---|
1235 | The C semantics work well for situations where manipulation of addresses is the primary meaning and data is rarely accessed, such as storage management (©malloc©/©free©). |
---|
1236 | |
---|
1237 | However, in most other situations, the pointed-to value is requested more often than the pointer address. |
---|
1238 | \begin{cfa} |
---|
1239 | *p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15); |
---|
1240 | \end{cfa} |
---|
1241 | In this case, it is tedious to explicitly write the dereferencing, and error prone when pointer arithmetic is allowed. |
---|
1242 | It is better to have the compiler generate the dereferencing and have no implicit pointer arithmetic: |
---|
1243 | \begin{cfa} |
---|
1244 | p2 = ((p1 + p2) * (p3 - p1)) / (p3 - 15); |
---|
1245 | \end{cfa} |
---|
1246 | |
---|
1247 | To support this common case, a reference type is introduced in \CFA, denoted by ©&©, which is the opposite dereference semantics to a pointer type, making the value at the pointed-to location the implicit semantics for dereferencing (similar but not the same as \CC \Index{reference type}s). |
---|
1248 | \begin{cfa} |
---|
1249 | int x, y, ®&® r1, ®&® r2, ®&&® r3; |
---|
1250 | ®&®r1 = &x; §\C{// r1 points to x}§ |
---|
1251 | ®&®r2 = &r1; §\C{// r2 points to x}§ |
---|
1252 | ®&®r1 = &y; §\C{// r1 points to y}§ |
---|
1253 | ®&&®r3 = ®&®&r2; §\C{// r3 points to r2}§ |
---|
1254 | r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15); §\C{// implicit dereferencing}§ |
---|
1255 | \end{cfa} |
---|
1256 | Except for auto-dereferencing by the compiler, this reference example is the same as the previous pointer example. |
---|
1257 | Hence, a reference behaves like the variable name for the current variable it is pointing-to. |
---|
1258 | One way to conceptualize a reference is via a rewrite rule, where the compiler inserts a dereference operator before the reference variable for each reference qualifier in a declaration, so the previous example becomes: |
---|
1259 | \begin{cfa} |
---|
1260 | ®*®r2 = ((®*®r1 + ®*®r2) ®*® (®**®r3 - ®*®r1)) / (®**®r3 - 15); |
---|
1261 | \end{cfa} |
---|
1262 | When a reference operation appears beside a dereference operation, \eg ©&*©, they cancel out. |
---|
1263 | However, in C, the cancellation always yields a value (\Index{rvalue}).\footnote{ |
---|
1264 | The unary ©&© operator yields the address of its operand. |
---|
1265 | If the operand has type ``type'', the result has type ``pointer to type''. |
---|
1266 | If 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}} |
---|
1267 | For a \CFA reference type, the cancellation on the left-hand side of assignment leaves the reference as an address (\Index{lvalue}): |
---|
1268 | \begin{cfa} |
---|
1269 | (&®*®)r1 = &x; §\C{// (\&*) cancel giving address in r1 not variable pointed-to by r1}§ |
---|
1270 | \end{cfa} |
---|
1271 | Similarly, the address of a reference can be obtained for assignment or computation (\Index{rvalue}): |
---|
1272 | \begin{cfa} |
---|
1273 | (&(&®*®)®*®)r3 = &(&®*®)r2; §\C{// (\&*) cancel giving address in r2, (\&(\&*)*) cancel giving address in r3}§ |
---|
1274 | \end{cfa} |
---|
1275 | Cancellation\index{cancellation!pointer/reference}\index{pointer!cancellation} works to arbitrary depth. |
---|
1276 | |
---|
1277 | Fundamentally, pointer and reference objects are functionally interchangeable because both contain addresses. |
---|
1278 | \begin{cfa} |
---|
1279 | int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, |
---|
1280 | &r1 = x, &&r2 = r1, &&&r3 = r2; |
---|
1281 | ***p3 = 3; §\C{// change x}§ |
---|
1282 | r3 = 3; §\C{// change x, ***r3}§ |
---|
1283 | **p3 = ...; §\C{// change p1}§ |
---|
1284 | &r3 = ...; §\C{// change r1, (\&*)**r3, 1 cancellation}§ |
---|
1285 | *p3 = ...; §\C{// change p2}§ |
---|
1286 | &&r3 = ...; §\C{// change r2, (\&(\&*)*)*r3, 2 cancellations}§ |
---|
1287 | &&&r3 = p3; §\C{// change r3 to p3, (\&(\&(\&*)*)*)r3, 3 cancellations}§ |
---|
1288 | \end{cfa} |
---|
1289 | Furthermore, both types are equally performant, as the same amount of dereferencing occurs for both types. |
---|
1290 | Therefore, the choice between them is based solely on whether the address is dereferenced frequently or infrequently, which dictates the amount of implicit dereferencing aid from the compiler. |
---|
1291 | |
---|
1292 | As for a pointer type, a reference type may have qualifiers: |
---|
1293 | \begin{cfa} |
---|
1294 | const int cx = 5; §\C{// cannot change cx;}§ |
---|
1295 | const int & cr = cx; §\C{// cannot change what cr points to}§ |
---|
1296 | ®&®cr = &cx; §\C{// can change cr}§ |
---|
1297 | cr = 7; §\C{// error, cannot change cx}§ |
---|
1298 | int & const rc = x; §\C{// must be initialized}§ |
---|
1299 | ®&®rc = &x; §\C{// error, cannot change rc}§ |
---|
1300 | const int & const crc = cx; §\C{// must be initialized}§ |
---|
1301 | crc = 7; §\C{// error, cannot change cx}§ |
---|
1302 | ®&®crc = &cx; §\C{// error, cannot change crc}§ |
---|
1303 | \end{cfa} |
---|
1304 | Hence, for type ©& const©, there is no pointer assignment, so ©&rc = &x© is disallowed, and \emph{the address value cannot be the null pointer unless an arbitrary pointer is coerced\index{coercion} into the reference}: |
---|
1305 | \begin{cfa} |
---|
1306 | int & const cr = *0; §\C{// where 0 is the int * zero}§ |
---|
1307 | \end{cfa} |
---|
1308 | Note, constant reference-types do not prevent \Index{addressing errors} because of explicit storage-management: |
---|
1309 | \begin{cfa} |
---|
1310 | int & const cr = *malloc(); |
---|
1311 | cr = 5; |
---|
1312 | free( &cr ); |
---|
1313 | cr = 7; §\C{// unsound pointer dereference}§ |
---|
1314 | \end{cfa} |
---|
1315 | |
---|
1316 | The position of the ©const© qualifier \emph{after} the pointer/reference qualifier causes confuse for C programmers. |
---|
1317 | The ©const© qualifier cannot be moved before the pointer/reference qualifier for C style-declarations; |
---|
1318 | \CFA-style declarations (see \VRef{s:Declarations}) attempt to address this issue: |
---|
1319 | \begin{quote2} |
---|
1320 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1321 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1322 | \begin{cfa} |
---|
1323 | ®const® * ®const® * const int ccp; |
---|
1324 | ®const® & ®const® & const int ccr; |
---|
1325 | \end{cfa} |
---|
1326 | & |
---|
1327 | \begin{cfa} |
---|
1328 | const int * ®const® * ®const® ccp; |
---|
1329 | |
---|
1330 | \end{cfa} |
---|
1331 | \end{tabular} |
---|
1332 | \end{quote2} |
---|
1333 | where the \CFA declaration is read left-to-right. |
---|
1334 | |
---|
1335 | Finally, like pointers, references are usable and composable with other type operators and generators. |
---|
1336 | \begin{cfa} |
---|
1337 | int w, x, y, z, & ar[3] = { x, y, z }; §\C{// initialize array of references}§ |
---|
1338 | &ar[1] = &w; §\C{// change reference array element}§ |
---|
1339 | typeof( ar[1] ) p; §\C{// (gcc) is int, i.e., the type of referenced object}§ |
---|
1340 | typeof( &ar[1] ) q; §\C{// (gcc) is int \&, i.e., the type of reference}§ |
---|
1341 | sizeof( ar[1] ) == sizeof( int ); §\C{// is true, i.e., the size of referenced object}§ |
---|
1342 | sizeof( &ar[1] ) == sizeof( int *) §\C{// is true, i.e., the size of a reference}§ |
---|
1343 | \end{cfa} |
---|
1344 | |
---|
1345 | In contrast to \CFA reference types, \Index*[C++]{\CC{}}'s reference types are all ©const© references, preventing changes to the reference address, so only value assignment is possible, which eliminates half of the \Index{address duality}. |
---|
1346 | Also, \CC does not allow \Index{array}s\index{array!reference} of reference\footnote{ |
---|
1347 | The reason for disallowing arrays of reference is unknown, but possibly comes from references being ethereal (like a textual macro), and hence, replaceable by the referant object.} |
---|
1348 | \Index*{Java}'s reference types to objects (all Java objects are on the heap) are like C pointers, which always manipulate the address, and there is no (bit-wise) object assignment, so objects are explicitly cloned by shallow or deep copying, which eliminates half of the address duality. |
---|
1349 | |
---|
1350 | |
---|
1351 | \subsection{Initialization} |
---|
1352 | |
---|
1353 | \Index{Initialization} is different than \Index{assignment} because initialization occurs on the empty (uninitialized) storage on an object, while assignment occurs on possibly initialized storage of an object. |
---|
1354 | There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, return/temporary binding. |
---|
1355 | Because the object being initialized has no value, there is only one meaningful semantics with respect to address duality: it must mean address as there is no pointed-to value. |
---|
1356 | In contrast, the left-hand side of assignment has an address that has a duality. |
---|
1357 | Therefore, for pointer/reference initialization, the initializing value must be an address not a value. |
---|
1358 | \begin{cfa} |
---|
1359 | int * p = &x; §\C{// assign address of x}§ |
---|
1360 | ®int * p = x;® §\C{// assign value of x}§ |
---|
1361 | int & r = x; §\C{// must have address of x}§ |
---|
1362 | \end{cfa} |
---|
1363 | Like the previous example with C pointer-arithmetic, it is unlikely assigning the value of ©x© into a pointer is meaningful (again, a warning is usually given). |
---|
1364 | Therefore, for safety, this context requires an address, so it is superfluous to require explicitly taking the address of the initialization object, even though the type is incorrect. |
---|
1365 | Note, this is strictly a convenience and safety feature for a programmer. |
---|
1366 | Hence, \CFA allows ©r© to be assigned ©x© because it infers a reference for ©x©, by implicitly inserting a address-of operator, ©&©, and it is an error to put an ©&© because the types no longer match due to the implicit dereference. |
---|
1367 | Unfortunately, C allows ©p© to be assigned with ©&x© (address) or ©x© (value), but most compilers warn about the latter assignment as being potentially incorrect. |
---|
1368 | Similarly, when a reference type is used for a parameter/return type, the call-site argument does not require a reference operator for the same reason. |
---|
1369 | \begin{cfa} |
---|
1370 | int & f( int & r ); §\C{// reference parameter and return}§ |
---|
1371 | z = f( x ) + f( y ); §\C{// reference operator added, temporaries needed for call results}§ |
---|
1372 | \end{cfa} |
---|
1373 | Within routine ©f©, it is possible to change the argument by changing the corresponding parameter, and parameter ©r© can be locally reassigned within ©f©. |
---|
1374 | Since operator routine ©?+?© takes its arguments by value, the references returned from ©f© are used to initialize compiler generated temporaries with value semantics that copy from the references. |
---|
1375 | \begin{cfa} |
---|
1376 | int temp1 = f( x ), temp2 = f( y ); |
---|
1377 | z = temp1 + temp2; |
---|
1378 | \end{cfa} |
---|
1379 | This \Index{implicit referencing} is crucial for reducing the syntactic burden for programmers when using references; |
---|
1380 | otherwise references have the same syntactic burden as pointers in these contexts. |
---|
1381 | |
---|
1382 | When a pointer/reference parameter has a ©const© value (immutable), it is possible to pass literals and expressions. |
---|
1383 | \begin{cfa} |
---|
1384 | void f( ®const® int & cr ); |
---|
1385 | void g( ®const® int * cp ); |
---|
1386 | f( 3 ); g( ®&®3 ); |
---|
1387 | f( x + y ); g( ®&®(x + y) ); |
---|
1388 | \end{cfa} |
---|
1389 | Here, 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. |
---|
1390 | The ©&© before the constant/expression for the pointer-type parameter (©g©) is a \CFA extension necessary to type match and is a common requirement before a variable in C (\eg ©scanf©). |
---|
1391 | Importantly, ©&3© may not be equal to ©&3©, where the references occur across calls because the temporaries maybe different on each call. |
---|
1392 | |
---|
1393 | \CFA \emph{extends} this semantics to a mutable pointer/reference parameter, and the compiler implicitly creates the necessary temporary (copying the argument), which is subsequently pointed-to by the reference parameter and can be changed.\footnote{ |
---|
1394 | If whole program analysis is possible, and shows the parameter is not assigned, \ie it is ©const©, the temporary is unnecessary.} |
---|
1395 | \begin{cfa} |
---|
1396 | void f( int & r ); |
---|
1397 | void g( int * p ); |
---|
1398 | f( 3 ); g( ®&®3 ); §\C{// compiler implicit generates temporaries}§ |
---|
1399 | f( x + y ); g( ®&®(x + y) ); §\C{// compiler implicit generates temporaries}§ |
---|
1400 | \end{cfa} |
---|
1401 | Essentially, there is an implicit \Index{rvalue} to \Index{lvalue} conversion in this case.\footnote{ |
---|
1402 | This 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.} |
---|
1403 | The implicit conversion allows seamless calls to any routine without having to explicitly name/copy the literal/expression to allow the call. |
---|
1404 | |
---|
1405 | %\CFA attempts to handle pointers and references in a uniform, symmetric manner. |
---|
1406 | Finally, C handles \Index{routine object}s in an inconsistent way. |
---|
1407 | A routine object is both a pointer and a reference (\Index{particle and wave}). |
---|
1408 | \begin{cfa} |
---|
1409 | void f( int i ); |
---|
1410 | void (*fp)( int ); §\C{// routine pointer}§ |
---|
1411 | fp = f; §\C{// reference initialization}§ |
---|
1412 | fp = &f; §\C{// pointer initialization}§ |
---|
1413 | fp = *f; §\C{// reference initialization}§ |
---|
1414 | fp(3); §\C{// reference invocation}§ |
---|
1415 | (*fp)(3); §\C{// pointer invocation}§ |
---|
1416 | \end{cfa} |
---|
1417 | While C's treatment of routine objects has similarity to inferring a reference type in initialization contexts, the examples are assignment not initialization, and all possible forms of assignment are possible (©f©, ©&f©, ©*f©) without regard for type. |
---|
1418 | Instead, a routine object should be referenced by a ©const© reference: |
---|
1419 | \begin{cfa} |
---|
1420 | ®const® void (®&® fr)( int ) = f; §\C{// routine reference}§ |
---|
1421 | fr = ... §\C{// error, cannot change code}§ |
---|
1422 | &fr = ...; §\C{// changing routine reference}§ |
---|
1423 | fr( 3 ); §\C{// reference call to f}§ |
---|
1424 | (*fr)(3); §\C{// error, incorrect type}§ |
---|
1425 | \end{cfa} |
---|
1426 | because the value of the routine object is a routine literal, \ie the routine code is normally immutable during execution.\footnote{ |
---|
1427 | Dynamic code rewriting is possible but only in special circumstances.} |
---|
1428 | \CFA allows this additional use of references for routine objects in an attempt to give a more consistent meaning for them. |
---|
1429 | |
---|
1430 | |
---|
1431 | \subsection{Address-of Semantics} |
---|
1432 | |
---|
1433 | In C, ©&E© is an rvalue for any expression ©E©. |
---|
1434 | \CFA extends the ©&© (address-of) operator as follows: |
---|
1435 | \begin{itemize} |
---|
1436 | \item |
---|
1437 | if ©R© is an \Index{rvalue} of type ©T &$_1$...&$_r$© where $r \ge 1$ references (©&© symbols) than ©&R© has type ©T ®*®&$_{\color{red}2}$...&$_{\color{red}r}$©, \ie ©T© pointer with $r-1$ references (©&© symbols). |
---|
1438 | |
---|
1439 | \item |
---|
1440 | if ©L© is an \Index{lvalue} of type ©T &$_1$...&$_l$© where $l \ge 0$ references (©&© symbols) then ©&L© has type ©T ®*®&$_{\color{red}1}$...&$_{\color{red}l}$©, \ie ©T© pointer with $l$ references (©&© symbols). |
---|
1441 | \end{itemize} |
---|
1442 | The following example shows the first rule applied to different \Index{rvalue} contexts: |
---|
1443 | \begin{cfa} |
---|
1444 | int x, * px, ** ppx, *** pppx, **** ppppx; |
---|
1445 | int & rx = x, && rrx = rx, &&& rrrx = rrx ; |
---|
1446 | x = rrrx; // rrrx is an lvalue with type int &&& (equivalent to x) |
---|
1447 | px = &rrrx; // starting from rrrx, &rrrx is an rvalue with type int *&&& (&x) |
---|
1448 | ppx = &&rrrx; // starting from &rrrx, &&rrrx is an rvalue with type int **&& (&rx) |
---|
1449 | pppx = &&&rrrx; // starting from &&rrrx, &&&rrrx is an rvalue with type int ***& (&rrx) |
---|
1450 | ppppx = &&&&rrrx; // starting from &&&rrrx, &&&&rrrx is an rvalue with type int **** (&rrrx) |
---|
1451 | \end{cfa} |
---|
1452 | The following example shows the second rule applied to different \Index{lvalue} contexts: |
---|
1453 | \begin{cfa} |
---|
1454 | int x, * px, ** ppx, *** pppx; |
---|
1455 | int & rx = x, && rrx = rx, &&& rrrx = rrx ; |
---|
1456 | rrrx = 2; // rrrx is an lvalue with type int &&& (equivalent to x) |
---|
1457 | &rrrx = px; // starting from rrrx, &rrrx is an rvalue with type int *&&& (rx) |
---|
1458 | &&rrrx = ppx; // starting from &rrrx, &&rrrx is an rvalue with type int **&& (rrx) |
---|
1459 | &&&rrrx = pppx; // starting from &&rrrx, &&&rrrx is an rvalue with type int ***& (rrrx) |
---|
1460 | \end{cfa} |
---|
1461 | |
---|
1462 | |
---|
1463 | \subsection{Conversions} |
---|
1464 | |
---|
1465 | C provides a basic implicit conversion to simplify variable usage: |
---|
1466 | \begin{enumerate} |
---|
1467 | \setcounter{enumi}{-1} |
---|
1468 | \item |
---|
1469 | lvalue to rvalue conversion: ©cv T© converts to ©T©, which allows implicit variable dereferencing. |
---|
1470 | \begin{cfa} |
---|
1471 | int x; |
---|
1472 | x + 1; // lvalue variable (int) converts to rvalue for expression |
---|
1473 | \end{cfa} |
---|
1474 | An rvalue has no type qualifiers (©cv©), so the lvalue qualifiers are dropped. |
---|
1475 | \end{enumerate} |
---|
1476 | \CFA provides three new implicit conversion for reference types to simplify reference usage. |
---|
1477 | \begin{enumerate} |
---|
1478 | \item |
---|
1479 | reference to rvalue conversion: ©cv T &© converts to ©T©, which allows implicit reference dereferencing. |
---|
1480 | \begin{cfa} |
---|
1481 | int x, &r = x, f( int p ); |
---|
1482 | x = ®r® + f( ®r® ); // lvalue reference converts to rvalue |
---|
1483 | \end{cfa} |
---|
1484 | An rvalue has no type qualifiers (©cv©), so the reference qualifiers are dropped. |
---|
1485 | |
---|
1486 | \item |
---|
1487 | lvalue to reference conversion: \lstinline[deletekeywords={lvalue}]@lvalue-type cv1 T@ converts to ©cv2 T &©, which allows implicitly converting variables to references. |
---|
1488 | \begin{cfa} |
---|
1489 | int x, &r = ®x®, f( int & p ); // lvalue variable (int) convert to reference (int &) |
---|
1490 | f( ®x® ); // lvalue variable (int) convert to reference (int &) |
---|
1491 | \end{cfa} |
---|
1492 | Conversion can restrict a type, where ©cv1© $\le$ ©cv2©, \eg passing an ©int© to a ©const volatile int &©, which has low cost. |
---|
1493 | Conversion can expand a type, where ©cv1© $>$ ©cv2©, \eg passing a ©const volatile int© to an ©int &©, which has high cost (\Index{warning}); |
---|
1494 | furthermore, if ©cv1© has ©const© but not ©cv2©, a temporary variable is created to preserve the immutable lvalue. |
---|
1495 | |
---|
1496 | \item |
---|
1497 | rvalue to reference conversion: ©T© converts to ©cv T &©, which allows binding references to temporaries. |
---|
1498 | \begin{cfa} |
---|
1499 | int x, & f( int & p ); |
---|
1500 | f( ®x + 3® ); // rvalue parameter (int) implicitly converts to lvalue temporary reference (int &) |
---|
1501 | ®&f®(...) = &x; // rvalue result (int &) implicitly converts to lvalue temporary reference (int &) |
---|
1502 | \end{cfa} |
---|
1503 | In both case, modifications to the temporary are inaccessible (\Index{warning}). |
---|
1504 | Conversion expands the temporary-type with ©cv©, which is low cost since the temporary is inaccessible. |
---|
1505 | \end{enumerate} |
---|
1506 | |
---|
1507 | |
---|
1508 | \begin{comment} |
---|
1509 | From: Richard Bilson <rcbilson@gmail.com> |
---|
1510 | Date: Wed, 13 Jul 2016 01:58:58 +0000 |
---|
1511 | Subject: Re: pointers / references |
---|
1512 | To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca> |
---|
1513 | |
---|
1514 | As a general comment I would say that I found the section confusing, as you move back and forth |
---|
1515 | between various real and imagined programming languages. If it were me I would rewrite into two |
---|
1516 | subsections, one that specifies precisely the syntax and semantics of reference variables and |
---|
1517 | another that provides the rationale. |
---|
1518 | |
---|
1519 | I don't see any obvious problems with the syntax or semantics so far as I understand them. It's not |
---|
1520 | obvious that the description you're giving is complete, but I'm sure you'll find the special cases |
---|
1521 | as you do the implementation. |
---|
1522 | |
---|
1523 | My big gripes are mostly that you're not being as precise as you need to be in your terminology, and |
---|
1524 | that you say a few things that aren't actually true even though I generally know what you mean. |
---|
1525 | |
---|
1526 | 20 C provides a pointer type; CFA adds a reference type. Both types contain an address, which is normally a |
---|
1527 | 21 location in memory. |
---|
1528 | |
---|
1529 | An address is not a location in memory; an address refers to a location in memory. Furthermore it |
---|
1530 | seems weird to me to say that a type "contains" an address; rather, objects of that type do. |
---|
1531 | |
---|
1532 | 21 Special addresses are used to denote certain states or access co-processor memory. By |
---|
1533 | 22 convention, no variable is placed at address 0, so addresses like 0, 1, 2, 3 are often used to denote no-value |
---|
1534 | 23 or other special states. |
---|
1535 | |
---|
1536 | This isn't standard C at all. There has to be one null pointer representation, but it doesn't have |
---|
1537 | to be a literal zero representation and there doesn't have to be more than one such representation. |
---|
1538 | |
---|
1539 | 23 Often dereferencing a special state causes a memory fault, so checking is necessary |
---|
1540 | 24 during execution. |
---|
1541 | |
---|
1542 | I don't see the connection between the two clauses here. I feel like if a bad pointer will not cause |
---|
1543 | a memory fault then I need to do more checking, not less. |
---|
1544 | |
---|
1545 | 24 If the programming language assigns addresses, a program's execution is sound, \ie all |
---|
1546 | 25 addresses are to valid memory locations. |
---|
1547 | |
---|
1548 | You haven't said what it means to "assign" an address, but if I use my intuitive understanding of |
---|
1549 | the term I don't see how this can be true unless you're assuming automatic storage management. |
---|
1550 | |
---|
1551 | 1 Program variables are implicit pointers to memory locations generated by the compiler and automatically |
---|
1552 | 2 dereferenced, as in: |
---|
1553 | |
---|
1554 | There is no reason why a variable needs to have a location in memory, and indeed in a typical |
---|
1555 | program many variables will not. In standard terminology an object identifier refers to data in the |
---|
1556 | execution environment, but not necessarily in memory. |
---|
1557 | |
---|
1558 | 13 A pointer/reference is a generalization of a variable name, \ie a mutable address that can point to more |
---|
1559 | 14 than one memory location during its lifetime. |
---|
1560 | |
---|
1561 | I feel like you're off the reservation here. In my world there are objects of pointer type, which |
---|
1562 | seem to be what you're describing here, but also pointer values, which can be stored in an object of |
---|
1563 | pointer type but don't necessarily have to be. For example, how would you describe the value denoted |
---|
1564 | by "&main" in a C program? I would call it a (function) pointer, but that doesn't satisfy your |
---|
1565 | definition. |
---|
1566 | |
---|
1567 | 16 not occupy storage as the literal is embedded directly into instructions.) Hence, a pointer occupies memory |
---|
1568 | 17 to store its current address, and the pointer's value is loaded by dereferencing, \eg: |
---|
1569 | |
---|
1570 | As with my general objection regarding your definition of variables, there is no reason why a |
---|
1571 | pointer variable (object of pointer type) needs to occupy memory. |
---|
1572 | |
---|
1573 | 21 p2 = p1 + x; // compiler infers *p2 = *p1 + x; |
---|
1574 | |
---|
1575 | What language are we in now? |
---|
1576 | |
---|
1577 | 24 pointer usage. However, in C, the following cases are ambiguous, especially with pointer arithmetic: |
---|
1578 | 25 p1 = p2; // p1 = p2 or *p1 = *p2 |
---|
1579 | |
---|
1580 | This isn't ambiguous. it's defined to be the first option. |
---|
1581 | |
---|
1582 | 26 p1 = p1 + 1; // p1 = p1 + 1 or *p1 = *p1 + 1 |
---|
1583 | |
---|
1584 | Again, this statement is not ambiguous. |
---|
1585 | |
---|
1586 | 13 example. Hence, a reference behaves like the variable name for the current variable it is pointing-to. The |
---|
1587 | 14 simplest way to understand a reference is to imagine the compiler inserting a dereference operator before |
---|
1588 | 15 the reference variable for each reference qualifier in a declaration, \eg: |
---|
1589 | |
---|
1590 | It's hard for me to understand who the audience for this part is. I think a practical programmer is |
---|
1591 | likely to be satisfied with "a reference behaves like the variable name for the current variable it |
---|
1592 | is pointing-to," maybe with some examples. Your "simplest way" doesn't strike me as simpler than |
---|
1593 | that. It feels like you're trying to provide a more precise definition for the semantics of |
---|
1594 | references, but it isn't actually precise enough to be a formal specification. If you want to |
---|
1595 | express the semantics of references using rewrite rules that's a great way to do it, but lay the |
---|
1596 | rules out clearly, and when you're showing an example of rewriting keep your |
---|
1597 | references/pointers/values separate (right now, you use \eg "r3" to mean a reference, a pointer, |
---|
1598 | and a value). |
---|
1599 | |
---|
1600 | 24 Cancellation works to arbitrary depth, and pointer and reference values are interchangeable because both |
---|
1601 | 25 contain addresses. |
---|
1602 | |
---|
1603 | Except they're not interchangeable, because they have different and incompatible types. |
---|
1604 | |
---|
1605 | 40 Interestingly, C++ deals with the address duality by making the pointed-to value the default, and prevent- |
---|
1606 | 41 ing changes to the reference address, which eliminates half of the duality. Java deals with the address duality |
---|
1607 | 42 by making address assignment the default and requiring field assignment (direct or indirect via methods), |
---|
1608 | 43 \ie there is no builtin bit-wise or method-wise assignment, which eliminates half of the duality. |
---|
1609 | |
---|
1610 | I can follow this but I think that's mostly because I already understand what you're trying to |
---|
1611 | say. I don't think I've ever heard the term "method-wise assignment" and I don't see you defining |
---|
1612 | it. Furthermore Java does have value assignment of basic (non-class) types, so your summary here |
---|
1613 | feels incomplete. (If it were me I'd drop this paragraph rather than try to save it.) |
---|
1614 | |
---|
1615 | 11 Hence, for type & const, there is no pointer assignment, so &rc = &x is disallowed, and the address value |
---|
1616 | 12 cannot be 0 unless an arbitrary pointer is assigned to the reference. |
---|
1617 | |
---|
1618 | Given the pains you've taken to motivate every little bit of the semantics up until now, this last |
---|
1619 | clause ("the address value cannot be 0") comes out of the blue. It seems like you could have |
---|
1620 | perfectly reasonable semantics that allowed the initialization of null references. |
---|
1621 | |
---|
1622 | 12 In effect, the compiler is managing the |
---|
1623 | 13 addresses for type & const not the programmer, and by a programming discipline of only using references |
---|
1624 | 14 with references, address errors can be prevented. |
---|
1625 | |
---|
1626 | Again, is this assuming automatic storage management? |
---|
1627 | |
---|
1628 | 18 rary binding. For reference initialization (like pointer), the initializing value must be an address (lvalue) not |
---|
1629 | 19 a value (rvalue). |
---|
1630 | |
---|
1631 | This sentence appears to suggest that an address and an lvalue are the same thing. |
---|
1632 | |
---|
1633 | 20 int * p = &x; // both &x and x are possible interpretations |
---|
1634 | |
---|
1635 | Are you saying that we should be considering "x" as a possible interpretation of the initializer |
---|
1636 | "&x"? It seems to me that this expression has only one legitimate interpretation in context. |
---|
1637 | |
---|
1638 | 21 int & r = x; // x unlikely interpretation, because of auto-dereferencing |
---|
1639 | |
---|
1640 | You mean, we can initialize a reference using an integer value? Surely we would need some sort of |
---|
1641 | cast to induce that interpretation, no? |
---|
1642 | |
---|
1643 | 22 Hence, the compiler implicitly inserts a reference operator, &, before the initialization expression. |
---|
1644 | |
---|
1645 | But then the expression would have pointer type, which wouldn't be compatible with the type of r. |
---|
1646 | |
---|
1647 | 22 Similarly, |
---|
1648 | 23 when a reference is used for a parameter/return type, the call-site argument does not require a reference |
---|
1649 | 24 operator. |
---|
1650 | |
---|
1651 | Furthermore, it would not be correct to use a reference operator. |
---|
1652 | |
---|
1653 | 45 The implicit conversion allows |
---|
1654 | 1 seamless calls to any routine without having to explicitly name/copy the literal/expression to allow the call. |
---|
1655 | 2 While C' attempts to handle pointers and references in a uniform, symmetric manner, C handles routine |
---|
1656 | 3 variables in an inconsistent way: a routine variable is both a pointer and a reference (particle and wave). |
---|
1657 | |
---|
1658 | After all this talk of how expressions can have both pointer and value interpretations, you're |
---|
1659 | disparaging C because it has expressions that have both pointer and value interpretations? |
---|
1660 | |
---|
1661 | On Sat, Jul 9, 2016 at 4:18 PM Peter A. Buhr <pabuhr@plg.uwaterloo.ca> wrote: |
---|
1662 | > Aaron discovered a few places where "&"s are missing and where there are too many "&", which are |
---|
1663 | > corrected in the attached updated. None of the text has changed, if you have started reading |
---|
1664 | > already. |
---|
1665 | \end{comment} |
---|
1666 | |
---|
1667 | |
---|
1668 | \section{Routine Definition} |
---|
1669 | |
---|
1670 | \CFA also supports a new syntax for routine definition, as well as \Celeven and K\&R routine syntax. |
---|
1671 | The point of the new syntax is to allow returning multiple values from a routine~\cite{Galletly96,CLU}, \eg: |
---|
1672 | \begin{cfa} |
---|
1673 | ®[ int o1, int o2, char o3 ]® f( int i1, char i2, char i3 ) { |
---|
1674 | §\emph{routine body}§ |
---|
1675 | } |
---|
1676 | \end{cfa} |
---|
1677 | where routine ©f© has three output (return values) and three input parameters. |
---|
1678 | Existing C syntax cannot be extended with multiple return types because it is impossible to embed a single routine name within multiple return type specifications. |
---|
1679 | |
---|
1680 | In 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{ |
---|
1681 | \Index*{Michael Tiemann}, with help from \Index*{Doug Lea}, provided named return values in g++, circa 1989.} |
---|
1682 | The value of each local return variable is automatically returned at routine termination. |
---|
1683 | Declaration qualifiers can only appear at the start of a routine definition, \eg: |
---|
1684 | \begin{cfa} |
---|
1685 | ®extern® [ int x ] g( int y ) {§\,§} |
---|
1686 | \end{cfa} |
---|
1687 | Lastly, if there are no output parameters or input parameters, the brackets and/or parentheses must still be specified; |
---|
1688 | in 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: |
---|
1689 | \begin{cfa} |
---|
1690 | [§\,§] g(); §\C{// no input or output parameters}§ |
---|
1691 | [ void ] g( void ); §\C{// no input or output parameters}§ |
---|
1692 | \end{cfa} |
---|
1693 | |
---|
1694 | Routine f is called as follows: |
---|
1695 | \begin{cfa} |
---|
1696 | [ i, j, ch ] = f( 3, 'a', ch ); |
---|
1697 | \end{cfa} |
---|
1698 | The 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. |
---|
1699 | |
---|
1700 | \CFA style declarations cannot be used to declare parameters for K\&R style routine definitions because of the following ambiguity: |
---|
1701 | \begin{cfa} |
---|
1702 | int (*f(x))[ 5 ] int x; {} |
---|
1703 | \end{cfa} |
---|
1704 | The 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. |
---|
1705 | Since the strings overlap starting with the open bracket, ©[©, there is an ambiguous interpretation for the string. |
---|
1706 | As well, \CFA-style declarations cannot be used to declare parameters for C-style routine-definitions because of the following ambiguity: |
---|
1707 | \begin{cfa} |
---|
1708 | typedef int foo; |
---|
1709 | int f( int (* foo) ); §\C{// foo is redefined as a parameter name}§ |
---|
1710 | \end{cfa} |
---|
1711 | The 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. |
---|
1712 | The 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. |
---|
1713 | The 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. |
---|
1714 | |
---|
1715 | C-style declarations can be used to declare parameters for \CFA style routine definitions, \eg: |
---|
1716 | \begin{cfa} |
---|
1717 | [ int ] f( * int, int * ); §\C{// returns an integer, accepts 2 pointers to integers}§ |
---|
1718 | [ * int, int * ] f( int ); §\C{// returns 2 pointers to integers, accepts an integer}§ |
---|
1719 | \end{cfa} |
---|
1720 | The 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: |
---|
1721 | \begin{cfa} |
---|
1722 | #define ptoa( n, d ) int (*n)[ d ] |
---|
1723 | int f( ptoa( p, 5 ) ) ... §\C{// expands to int f( int (*p)[ 5 ] )}§ |
---|
1724 | [ int ] f( ptoa( p, 5 ) ) ... §\C{// expands to [ int ] f( int (*p)[ 5 ] )}§ |
---|
1725 | \end{cfa} |
---|
1726 | Again, programmers are highly encouraged to use one declaration form or the other, rather than mixing the forms. |
---|
1727 | |
---|
1728 | |
---|
1729 | \subsection{Named Return Values} |
---|
1730 | |
---|
1731 | \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: |
---|
1732 | \begin{cfa} |
---|
1733 | int f() { |
---|
1734 | int x; |
---|
1735 | ... x = 0; ... x = y; ... |
---|
1736 | return x; |
---|
1737 | } |
---|
1738 | \end{cfa} |
---|
1739 | Because 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: |
---|
1740 | \newline |
---|
1741 | \begin{minipage}{\linewidth} |
---|
1742 | \begin{cfa} |
---|
1743 | ®[ int x, int y ]® f() { |
---|
1744 | int z; |
---|
1745 | ... x = 0; ... y = z; ... |
---|
1746 | ®return;® §\C{// implicitly return x, y}§ |
---|
1747 | } |
---|
1748 | \end{cfa} |
---|
1749 | \end{minipage} |
---|
1750 | \newline |
---|
1751 | When the return is encountered, the current values of ©x© and ©y© are returned to the calling routine. |
---|
1752 | As well, ``falling off the end'' of a routine without a ©return© statement is permitted, as in: |
---|
1753 | \begin{cfa} |
---|
1754 | [ int x, int y ] f() { |
---|
1755 | ... |
---|
1756 | } §\C{// implicitly return x, y}§ |
---|
1757 | \end{cfa} |
---|
1758 | In this case, the current values of ©x© and ©y© are returned to the calling routine just as if a ©return© had been encountered. |
---|
1759 | |
---|
1760 | Named return values may be used in conjunction with named parameter values; |
---|
1761 | specifically, a return and parameter can have the same name. |
---|
1762 | \begin{cfa} |
---|
1763 | [ int x, int y ] f( int, x, int y ) { |
---|
1764 | ... |
---|
1765 | } §\C{// implicitly return x, y}§ |
---|
1766 | \end{cfa} |
---|
1767 | This notation allows the compiler to eliminate temporary variables in nested routine calls. |
---|
1768 | \begin{cfa} |
---|
1769 | [ int x, int y ] f( int, x, int y ); §\C{// prototype declaration}§ |
---|
1770 | int a, b; |
---|
1771 | [a, b] = f( f( f( a, b ) ) ); |
---|
1772 | \end{cfa} |
---|
1773 | While the compiler normally ignores parameters names in prototype declarations, here they are used to eliminate temporary return-values by inferring that the results of each call are the inputs of the next call, and ultimately, the left-hand side of the assignment. |
---|
1774 | Hence, even without the body of routine ©f© (separate compilation), it is possible to perform a global optimization across routine calls. |
---|
1775 | The compiler warns about naming inconsistencies between routine prototype and definition in this case, and behaviour is \Index{undefined} if the programmer is inconsistent. |
---|
1776 | |
---|
1777 | |
---|
1778 | \subsection{Routine Prototype} |
---|
1779 | |
---|
1780 | The syntax of the new routine prototype declaration follows directly from the new routine definition syntax; |
---|
1781 | as well, parameter names are optional, \eg: |
---|
1782 | \begin{cfa} |
---|
1783 | [ int x ] f (); §\C{// returning int with no parameters}§ |
---|
1784 | [ * int ] g (int y); §\C{// returning pointer to int with int parameter}§ |
---|
1785 | [ ] h ( int, char ); §\C{// returning no result with int and char parameters}§ |
---|
1786 | [ * int, int ] j ( int ); §\C{// returning pointer to int and int, with int parameter}§ |
---|
1787 | \end{cfa} |
---|
1788 | This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa). |
---|
1789 | It is possible to declare multiple routine-prototypes in a single declaration, but the entire type specification is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), \eg: |
---|
1790 | \begin{quote2} |
---|
1791 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1792 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1793 | \begin{cfa} |
---|
1794 | [ int ] f( int ), g; |
---|
1795 | \end{cfa} |
---|
1796 | & |
---|
1797 | \begin{cfa} |
---|
1798 | int f( int ), g( int ); |
---|
1799 | \end{cfa} |
---|
1800 | \end{tabular} |
---|
1801 | \end{quote2} |
---|
1802 | Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} \eg: |
---|
1803 | \begin{cfa} |
---|
1804 | extern [ int ] f ( int ); |
---|
1805 | static [ int ] g ( int ); |
---|
1806 | \end{cfa} |
---|
1807 | |
---|
1808 | |
---|
1809 | \section{Routine Pointers} |
---|
1810 | |
---|
1811 | The syntax for pointers to \CFA routines specifies the pointer name on the right, \eg: |
---|
1812 | \begin{cfa} |
---|
1813 | * [ int x ] () fp; §\C{// pointer to routine returning int with no parameters}§ |
---|
1814 | * [ * int ] (int y) gp; §\C{// pointer to routine returning pointer to int with int parameter}§ |
---|
1815 | * [ ] (int,char) hp; §\C{// pointer to routine returning no result with int and char parameters}§ |
---|
1816 | * [ * int,int ] ( int ) jp; §\C{// pointer to routine returning pointer to int and int, with int parameter}§ |
---|
1817 | \end{cfa} |
---|
1818 | While parameter names are optional, \emph{a routine name cannot be specified}; |
---|
1819 | for example, the following is incorrect: |
---|
1820 | \begin{cfa} |
---|
1821 | * [ int x ] f () fp; §\C{// routine name "f" is not allowed}§ |
---|
1822 | \end{cfa} |
---|
1823 | |
---|
1824 | |
---|
1825 | \section{Named and Default Arguments} |
---|
1826 | |
---|
1827 | Named\index{named arguments}\index{arguments!named} and default\index{default arguments}\index{arguments!default} arguments~\cite{Hardgrave76}\footnote{ |
---|
1828 | Francez~\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.} |
---|
1829 | are two mechanisms to simplify routine call. |
---|
1830 | Both mechanisms are discussed with respect to \CFA. |
---|
1831 | \begin{description} |
---|
1832 | \item[Named (or Keyword) Arguments:] |
---|
1833 | provide the ability to specify an argument to a routine call using the parameter name rather than the position of the parameter. |
---|
1834 | For example, given the routine: |
---|
1835 | \begin{cfa} |
---|
1836 | void p( int x, int y, int z ) {...} |
---|
1837 | \end{cfa} |
---|
1838 | a positional call is: |
---|
1839 | \begin{cfa} |
---|
1840 | p( 4, 7, 3 ); |
---|
1841 | \end{cfa} |
---|
1842 | whereas a named (keyword) call may be: |
---|
1843 | \begin{cfa} |
---|
1844 | p( z : 3, x : 4, y : 7 ); §\C{// rewrite $\Rightarrow$ p( 4, 7, 3 )}§ |
---|
1845 | \end{cfa} |
---|
1846 | Here the order of the arguments is unimportant, and the names of the parameters are used to associate argument values with the corresponding parameters. |
---|
1847 | The compiler rewrites a named call into a positional call. |
---|
1848 | The advantages of named parameters are: |
---|
1849 | \begin{itemize} |
---|
1850 | \item |
---|
1851 | Remembering the names of the parameters may be easier than the order in the routine definition. |
---|
1852 | \item |
---|
1853 | Parameter names provide documentation at the call site (assuming the names are descriptive). |
---|
1854 | \item |
---|
1855 | Changes can be made to the order or number of parameters without affecting the call (although the call must still be recompiled). |
---|
1856 | \end{itemize} |
---|
1857 | |
---|
1858 | Unfortunately, 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. |
---|
1859 | For example, the following routine prototypes and definition are all valid. |
---|
1860 | \begin{cfa} |
---|
1861 | void p( int, int, int ); §\C{// equivalent prototypes}§ |
---|
1862 | void p( int x, int y, int z ); |
---|
1863 | void p( int y, int x, int z ); |
---|
1864 | void p( int z, int y, int x ); |
---|
1865 | void p( int q, int r, int s ) {} §\C{// match with this definition}§ |
---|
1866 | \end{cfa} |
---|
1867 | Forcing matching parameter names in routine prototypes with corresponding routine definitions is possible, but goes against a strong tradition in C programming. |
---|
1868 | Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports. |
---|
1869 | The former is easy to do, while the latter is more complex. |
---|
1870 | |
---|
1871 | Furthermore, named arguments do not work well in a \CFA-style programming-languages because they potentially introduces a new criteria for type matching. |
---|
1872 | For example, it is technically possible to disambiguate between these two overloaded definitions of ©f© based on named arguments at the call site: |
---|
1873 | \begin{cfa} |
---|
1874 | int f( int i, int j ); |
---|
1875 | int f( int x, double y ); |
---|
1876 | |
---|
1877 | f( j : 3, i : 4 ); §\C{// 1st f}§ |
---|
1878 | f( x : 7, y : 8.1 ); §\C{// 2nd f}§ |
---|
1879 | f( 4, 5 ); §\C{// ambiguous call}§ |
---|
1880 | \end{cfa} |
---|
1881 | However, named arguments compound routine resolution in conjunction with conversions: |
---|
1882 | \begin{cfa} |
---|
1883 | f( i : 3, 5.7 ); §\C{// ambiguous call ?}§ |
---|
1884 | \end{cfa} |
---|
1885 | Depending on the cost associated with named arguments, this call could be resolvable or ambiguous. |
---|
1886 | Adding named argument into the routine resolution algorithm does not seem worth the complexity. |
---|
1887 | Therefore, \CFA does \emph{not} attempt to support named arguments. |
---|
1888 | |
---|
1889 | \item[Default Arguments] |
---|
1890 | provide the ability to associate a default value with a parameter so it can be optionally specified in the argument list. |
---|
1891 | For example, given the routine: |
---|
1892 | \begin{cfa} |
---|
1893 | void p( int x = 1, int y = 2, int z = 3 ) {...} |
---|
1894 | \end{cfa} |
---|
1895 | the allowable positional calls are: |
---|
1896 | \begin{cfa} |
---|
1897 | p(); §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§ |
---|
1898 | p( 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§ |
---|
1899 | p( 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§ |
---|
1900 | p( 4, 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 4 )}§ |
---|
1901 | // empty arguments |
---|
1902 | p( , 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 1, 4, 4 )}§ |
---|
1903 | p( 4, , 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 4 )}§ |
---|
1904 | p( 4, 4, ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§ |
---|
1905 | p( 4, , ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§ |
---|
1906 | p( , 4, ); §\C{// rewrite $\Rightarrow$ p( 1, 4, 3 )}§ |
---|
1907 | p( , , 4 ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 4 )}§ |
---|
1908 | p( , , ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§ |
---|
1909 | \end{cfa} |
---|
1910 | Here the missing arguments are inserted from the default values in the parameter list. |
---|
1911 | The compiler rewrites missing default values into explicit positional arguments. |
---|
1912 | The advantages of default values are: |
---|
1913 | \begin{itemize} |
---|
1914 | \item |
---|
1915 | Routines with a large number of parameters are often very generalized, giving a programmer a number of different options on how a computation is performed. |
---|
1916 | For many of these kinds of routines, there are standard or default settings that work for the majority of computations. |
---|
1917 | Without 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. |
---|
1918 | \item |
---|
1919 | When a routine's interface is augmented with new parameters, it extends the interface providing generalizability\footnote{ |
---|
1920 | ``It should be possible for the implementor of an abstraction to increase its generality. |
---|
1921 | So long as the modified abstraction is a generalization of the original, existing uses of the abstraction will not require change. |
---|
1922 | It 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. |
---|
1923 | This 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}} |
---|
1924 | (somewhat like the generalization provided by inheritance for classes). |
---|
1925 | That is, all existing calls are still valid, although the call must still be recompiled. |
---|
1926 | \end{itemize} |
---|
1927 | The only disadvantage of default arguments is that unintentional omission of an argument may not result in a compiler-time error. |
---|
1928 | Instead, a default value is used, which may not be the programmer's intent. |
---|
1929 | |
---|
1930 | Default values may only appear in a prototype versus definition context: |
---|
1931 | \begin{cfa} |
---|
1932 | void p( int x, int y = 2, int z = 3 ); §\C{// prototype: allowed}§ |
---|
1933 | void p( int, int = 2, int = 3 ); §\C{// prototype: allowed}§ |
---|
1934 | void p( int x, int y = 2, int z = 3 ) {} §\C{// definition: not allowed}§ |
---|
1935 | \end{cfa} |
---|
1936 | The reason for this restriction is to allow separate compilation. |
---|
1937 | Multiple prototypes with different default values is an error. |
---|
1938 | \end{description} |
---|
1939 | |
---|
1940 | Ellipse (``...'') arguments present problems when used with default arguments. |
---|
1941 | The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities: |
---|
1942 | \begin{cfa} |
---|
1943 | p( /* positional */, ... , /* named */ ); |
---|
1944 | p( /* positional */, /* named */, ... ); |
---|
1945 | \end{cfa} |
---|
1946 | While it is possible to implement both approaches, the first possibly is more complex than the second, \eg: |
---|
1947 | \begin{cfa} |
---|
1948 | p( int x, int y, int z, ... ); |
---|
1949 | p( 1, 4, 5, 6, z : 3, y : 2 ); §\C{// assume p( /* positional */, ... , /* named */ );}§ |
---|
1950 | p( 1, z : 3, y : 2, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, ... );}§ |
---|
1951 | \end{cfa} |
---|
1952 | In 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. |
---|
1953 | Hence, this approach seems significantly more difficult, and hence, confusing and error prone. |
---|
1954 | In the second call, the named arguments separate the positional and ellipse arguments, making it trivial to read the call. |
---|
1955 | |
---|
1956 | The problem is exacerbated with default arguments, \eg: |
---|
1957 | \begin{cfa} |
---|
1958 | void p( int x, int y = 2, int z = 3... ); |
---|
1959 | p( 1, 4, 5, 6, z : 3 ); §\C{// assume p( /* positional */, ... , /* named */ );}§ |
---|
1960 | p( 1, z : 3, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, ... );}§ |
---|
1961 | \end{cfa} |
---|
1962 | The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments; |
---|
1963 | therefore, argument 5 subsequently conflicts with the named argument z : 3. |
---|
1964 | In 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. |
---|
1965 | For these reasons, \CFA requires named arguments before ellipse arguments. |
---|
1966 | Finally, 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. |
---|
1967 | |
---|
1968 | Default arguments and overloading (see Section 24) are complementary. |
---|
1969 | While in theory default arguments can be simulated with overloading, as in: |
---|
1970 | \begin{quote2} |
---|
1971 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1972 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{default arguments}} & \multicolumn{1}{c}{\textbf{overloading}} \\ |
---|
1973 | \begin{cfa} |
---|
1974 | void p( int x, int y = 2, int z = 3 ) {...} |
---|
1975 | |
---|
1976 | |
---|
1977 | \end{cfa} |
---|
1978 | & |
---|
1979 | \begin{cfa} |
---|
1980 | void p( int x, int y, int z ) {...} |
---|
1981 | void p( int x ) { p( x, 2, 3 ); } |
---|
1982 | void p( int x, int y ) { p( x, y, 3 ); } |
---|
1983 | \end{cfa} |
---|
1984 | \end{tabular} |
---|
1985 | \end{quote2} |
---|
1986 | the number of required overloaded routines is linear in the number of default values, which is unacceptable growth. |
---|
1987 | In general, overloading should only be used over default arguments if the body of the routine is significantly different. |
---|
1988 | Furthermore, overloading cannot handle accessing default arguments in the middle of a positional list, via a missing argument, such as: |
---|
1989 | \begin{cfa} |
---|
1990 | p( 1, /* default */, 5 ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 5 )}§ |
---|
1991 | \end{cfa} |
---|
1992 | |
---|
1993 | Given the \CFA restrictions above, both named and default arguments are backwards compatible. |
---|
1994 | \Index*[C++]{\CC{}} only supports default arguments; |
---|
1995 | \Index*{Ada} supports both named and default arguments. |
---|
1996 | |
---|
1997 | |
---|
1998 | \section{Unnamed Structure Fields} |
---|
1999 | |
---|
2000 | C requires each field of a structure to have a name, except for a bit field associated with a basic type, \eg: |
---|
2001 | \begin{cfa} |
---|
2002 | struct { |
---|
2003 | int f1; §\C{// named field}§ |
---|
2004 | int f2 : 4; §\C{// named field with bit field size}§ |
---|
2005 | int : 3; §\C{// unnamed field for basic type with bit field size}§ |
---|
2006 | int ; §\C{// disallowed, unnamed field}§ |
---|
2007 | int *; §\C{// disallowed, unnamed field}§ |
---|
2008 | int (*)( int ); §\C{// disallowed, unnamed field}§ |
---|
2009 | }; |
---|
2010 | \end{cfa} |
---|
2011 | This requirement is relaxed by making the field name optional for all field declarations; therefore, all the field declarations in the example are allowed. |
---|
2012 | As for unnamed bit fields, an unnamed field is used for padding a structure to a particular size. |
---|
2013 | A list of unnamed fields is also supported, \eg: |
---|
2014 | \begin{cfa} |
---|
2015 | struct { |
---|
2016 | int , , ; §\C{// 3 unnamed fields}§ |
---|
2017 | } |
---|
2018 | \end{cfa} |
---|
2019 | |
---|
2020 | |
---|
2021 | \section{Nesting} |
---|
2022 | |
---|
2023 | Nesting of types and routines is useful for controlling name visibility (\newterm{name hiding}). |
---|
2024 | |
---|
2025 | |
---|
2026 | \subsection{Type Nesting} |
---|
2027 | |
---|
2028 | \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. |
---|
2029 | \begin{figure} |
---|
2030 | \centering |
---|
2031 | \begin{tabular}{@{}l@{\hspace{3em}}l|l@{}} |
---|
2032 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{C Type Nesting}} & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}} & \multicolumn{1}{|c}{\textbf{\CFA}} \\ |
---|
2033 | \hline |
---|
2034 | \begin{cfa} |
---|
2035 | struct S { |
---|
2036 | enum C { R, G, B }; |
---|
2037 | struct T { |
---|
2038 | union U { int i, j; }; |
---|
2039 | enum C c; |
---|
2040 | short int i, j; |
---|
2041 | }; |
---|
2042 | struct T t; |
---|
2043 | } s; |
---|
2044 | |
---|
2045 | int fred() { |
---|
2046 | s.t.c = R; |
---|
2047 | struct T t = { R, 1, 2 }; |
---|
2048 | enum C c; |
---|
2049 | union U u; |
---|
2050 | } |
---|
2051 | \end{cfa} |
---|
2052 | & |
---|
2053 | \begin{cfa} |
---|
2054 | enum C { R, G, B }; |
---|
2055 | union U { int i, j; }; |
---|
2056 | struct T { |
---|
2057 | enum C c; |
---|
2058 | short int i, j; |
---|
2059 | }; |
---|
2060 | struct S { |
---|
2061 | struct T t; |
---|
2062 | } s; |
---|
2063 | |
---|
2064 | |
---|
2065 | |
---|
2066 | |
---|
2067 | |
---|
2068 | |
---|
2069 | |
---|
2070 | \end{cfa} |
---|
2071 | & |
---|
2072 | \begin{cfa} |
---|
2073 | struct S { |
---|
2074 | enum C { R, G, B }; |
---|
2075 | struct T { |
---|
2076 | union U { int i, j; }; |
---|
2077 | enum C c; |
---|
2078 | short int i, j; |
---|
2079 | }; |
---|
2080 | struct T t; |
---|
2081 | } s; |
---|
2082 | |
---|
2083 | int fred() { |
---|
2084 | s.t.c = ®S.®R; // type qualification |
---|
2085 | struct ®S.®T t = { ®S.®R, 1, 2 }; |
---|
2086 | enum ®S.®C c; |
---|
2087 | union ®S.T.®U u; |
---|
2088 | } |
---|
2089 | \end{cfa} |
---|
2090 | \end{tabular} |
---|
2091 | \caption{Type Nesting / Qualification} |
---|
2092 | \label{f:TypeNestingQualification} |
---|
2093 | \end{figure} |
---|
2094 | In the left example in C, types ©C©, ©U© and ©T© are implicitly hoisted outside of type ©S© into the containing block scope. |
---|
2095 | In the right example in \CFA, the types are not hoisted and accessed using the field-selection operator ``©.©'' for type qualification, as does \Index*{Java}, rather than the \CC type-selection operator ``©::©''. |
---|
2096 | |
---|
2097 | |
---|
2098 | \subsection{Routine Nesting} |
---|
2099 | |
---|
2100 | While \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. |
---|
2101 | For example, the C quick-sort is wrapped into the following polymorphic \CFA routine: |
---|
2102 | \begin{cfa} |
---|
2103 | forall( otype T | { int ?<?( T, T ); } ) |
---|
2104 | void qsort( const T * arr, size_t dimension ); |
---|
2105 | \end{cfa} |
---|
2106 | which can be used to sort in ascending and descending order by locally redefining the less-than operator into greater-than. |
---|
2107 | \begin{cfa} |
---|
2108 | const unsigned int size = 5; |
---|
2109 | int ia[size]; |
---|
2110 | ... §\C{// assign values to array ia}§ |
---|
2111 | qsort( ia, size ); §\C{// sort ascending order using builtin ?<?}§ |
---|
2112 | { |
---|
2113 | ®int ?<?( int x, int y ) { return x > y; }® §\C{// nested routine}§ |
---|
2114 | qsort( ia, size ); §\C{// sort descending order by local redefinition}§ |
---|
2115 | } |
---|
2116 | \end{cfa} |
---|
2117 | |
---|
2118 | Nested routines are not first-class, meaning a nested routine cannot be returned if it has references to variables in its enclosing blocks; |
---|
2119 | the only exception is references to the external block of the translation unit, as these variables persist for the duration of the program. |
---|
2120 | The following program in undefined in \CFA (and Indexc{gcc}) |
---|
2121 | \begin{cfa} |
---|
2122 | [* [int]( int )] foo() { §\C{// int (*foo())( int )}§ |
---|
2123 | int ®i® = 7; |
---|
2124 | int bar( int p ) { |
---|
2125 | ®i® += 1; §\C{// dependent on local variable}§ |
---|
2126 | sout | ®i® | endl; |
---|
2127 | } |
---|
2128 | return bar; §\C{// undefined because of local dependence}§ |
---|
2129 | } |
---|
2130 | int main() { |
---|
2131 | * [int]( int ) fp = foo(); §\C{// int (*fp)( int )}§ |
---|
2132 | sout | fp( 3 ) | endl; |
---|
2133 | } |
---|
2134 | \end{cfa} |
---|
2135 | because |
---|
2136 | |
---|
2137 | Currently, there are no \Index{lambda} expressions, \ie unnamed routines because routine names are very important to properly select the correct routine. |
---|
2138 | |
---|
2139 | |
---|
2140 | \section{Tuples} |
---|
2141 | |
---|
2142 | In C and \CFA, lists of elements appear in several contexts, such as the parameter list for a routine call. |
---|
2143 | (More contexts are added shortly.) |
---|
2144 | A list of such elements is called a \newterm{lexical list}. |
---|
2145 | The general syntax of a lexical list is: |
---|
2146 | \begin{cfa} |
---|
2147 | [ §\emph{exprlist}§ ] |
---|
2148 | \end{cfa} |
---|
2149 | where ©$\emph{exprlist}$© is a list of one or more expressions separated by commas. |
---|
2150 | The brackets, ©[]©, allow differentiating between lexical lists and expressions containing the C comma operator. |
---|
2151 | The following are examples of lexical lists: |
---|
2152 | \begin{cfa} |
---|
2153 | [ x, y, z ] |
---|
2154 | [ 2 ] |
---|
2155 | [ v+w, x*y, 3.14159, f() ] |
---|
2156 | \end{cfa} |
---|
2157 | Tuples are permitted to contain sub-tuples (\ie nesting), such as ©[ [ 14, 21 ], 9 ]©, which is a 2-element tuple whose first element is itself a tuple. |
---|
2158 | Note, a tuple is not a record (structure); |
---|
2159 | a record denotes a single value with substructure, whereas a tuple is multiple values with no substructure (see flattening coercion in Section 12.1). |
---|
2160 | In essence, tuples are largely a compile time phenomenon, having little or no runtime presence. |
---|
2161 | |
---|
2162 | Tuples can be organized into compile-time tuple variables; |
---|
2163 | these variables are of \newterm{tuple type}. |
---|
2164 | Tuple variables and types can be used anywhere lists of conventional variables and types can be used. |
---|
2165 | The general syntax of a tuple type is: |
---|
2166 | \begin{cfa} |
---|
2167 | [ §\emph{typelist}§ ] |
---|
2168 | \end{cfa} |
---|
2169 | where ©$\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. |
---|
2170 | Examples of tuple types include: |
---|
2171 | \begin{cfa} |
---|
2172 | [ unsigned int, char ] |
---|
2173 | [ double, double, double ] |
---|
2174 | [ * int, int * ] §\C{// mix of CFA and ANSI}§ |
---|
2175 | [ * [ 5 ] int, * * char, * [ [ int, int ] ] (int, int) ] |
---|
2176 | \end{cfa} |
---|
2177 | Like 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. |
---|
2178 | |
---|
2179 | Examples of declarations using tuple types are: |
---|
2180 | \begin{cfa} |
---|
2181 | [ int, int ] x; §\C{// 2 element tuple, each element of type int}§ |
---|
2182 | * [ char, char ] y; §\C{// pointer to a 2 element tuple}§ |
---|
2183 | [ [ int, int ] ] z ([ int, int ]); |
---|
2184 | \end{cfa} |
---|
2185 | The 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. |
---|
2186 | |
---|
2187 | As mentioned, tuples can appear in contexts requiring a list of value, such as an argument list of a routine call. |
---|
2188 | In unambiguous situations, the tuple brackets may be omitted, \eg a tuple that appears as an argument may have its |
---|
2189 | square brackets omitted for convenience; therefore, the following routine invocations are equivalent: |
---|
2190 | \begin{cfa} |
---|
2191 | f( [ 1, x+2, fred() ] ); |
---|
2192 | f( 1, x+2, fred() ); |
---|
2193 | \end{cfa} |
---|
2194 | Also, 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. |
---|
2195 | For example, the following are all legal: |
---|
2196 | \begin{cfa} |
---|
2197 | [ int, int ] w1; |
---|
2198 | [ int, int, int ] w2; |
---|
2199 | [ void ] f (int, int, int); /* three input parameters of type int */ |
---|
2200 | [ void ] g ([ int, int, int ]); /* 3 element tuple as input */ |
---|
2201 | f( [ 1, 2, 3 ] ); |
---|
2202 | f( w1, 3 ); |
---|
2203 | f( 1, w1 ); |
---|
2204 | f( w2 ); |
---|
2205 | g( [ 1, 2, 3 ] ); |
---|
2206 | g( w1, 3 ); |
---|
2207 | g( 1, w1 ); |
---|
2208 | g( w2 ); |
---|
2209 | \end{cfa} |
---|
2210 | Note, in all cases 3 arguments are supplied even though the syntax may appear to supply less than 3. As mentioned, a |
---|
2211 | tuple does not have structure like a record; a tuple is simply converted into a list of components. |
---|
2212 | \begin{rationale} |
---|
2213 | The present implementation of \CFA does not support nested routine calls when the inner routine returns multiple values; \ie a statement such as ©g( f() )© is not supported. |
---|
2214 | Using a temporary variable to store the results of the inner routine and then passing this variable to the outer routine works, however. |
---|
2215 | \end{rationale} |
---|
2216 | |
---|
2217 | A tuple can contain a C comma expression, provided the expression containing the comma operator is enclosed in parentheses. |
---|
2218 | For instance, the following tuples are equivalent: |
---|
2219 | \begin{cfa} |
---|
2220 | [ 1, 3, 5 ] |
---|
2221 | [ 1, (2, 3), 5 ] |
---|
2222 | \end{cfa} |
---|
2223 | The second element of the second tuple is the expression (2, 3), which yields the result 3. |
---|
2224 | This requirement is the same as for comma expressions in argument lists. |
---|
2225 | |
---|
2226 | Type qualifiers, \ie const and volatile, may modify a tuple type. |
---|
2227 | The 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)], \ie the qualifier is distributed across all of the types in the tuple, \eg: |
---|
2228 | \begin{cfa} |
---|
2229 | const volatile [ int, float, const int ] x; |
---|
2230 | \end{cfa} |
---|
2231 | is equivalent to: |
---|
2232 | \begin{cfa} |
---|
2233 | [ const volatile int, const volatile float, const volatile int ] x; |
---|
2234 | \end{cfa} |
---|
2235 | Declaration qualifiers can only appear at the start of a \CFA tuple declaration4, \eg: |
---|
2236 | \begin{cfa} |
---|
2237 | extern [ int, int ] w1; |
---|
2238 | static [ int, int, int ] w2; |
---|
2239 | \end{cfa} |
---|
2240 | \begin{rationale} |
---|
2241 | Unfortunately, C's syntax for subscripts precluded treating them as tuples. |
---|
2242 | The C subscript list has the form ©[i][j]...© and not ©[i, j, ...]©. |
---|
2243 | Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, \eg ©f[g()]© always means a single subscript value because there is only one set of brackets. |
---|
2244 | Fixing 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. |
---|
2245 | \end{rationale} |
---|
2246 | |
---|
2247 | |
---|
2248 | \subsection{Tuple Coercions} |
---|
2249 | |
---|
2250 | There are four coercions that can be performed on tuples and tuple variables: closing, opening, flattening and structuring. |
---|
2251 | In addition, the coercion of dereferencing can be performed on a tuple variable to yield its value(s), as for other variables. |
---|
2252 | A \newterm{closing coercion} takes a set of values and converts it into a tuple value, which is a contiguous set of values, as in: |
---|
2253 | \begin{cfa} |
---|
2254 | [ int, int, int, int ] w; |
---|
2255 | w = [ 1, 2, 3, 4 ]; |
---|
2256 | \end{cfa} |
---|
2257 | First the right-hand tuple is closed into a tuple value and then the tuple value is assigned. |
---|
2258 | |
---|
2259 | An \newterm{opening coercion} is the opposite of closing; a tuple value is converted into a tuple of values, as in: |
---|
2260 | \begin{cfa} |
---|
2261 | [ a, b, c, d ] = w |
---|
2262 | \end{cfa} |
---|
2263 | ©w© is implicitly opened to yield a tuple of four values, which are then assigned individually. |
---|
2264 | |
---|
2265 | A \newterm{flattening coercion} coerces a nested tuple, \ie 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: |
---|
2266 | \begin{cfa} |
---|
2267 | [ a, b, c, d ] = [ 1, [ 2, 3 ], 4 ]; |
---|
2268 | \end{cfa} |
---|
2269 | First the right-hand tuple is flattened and then the values are assigned individually. |
---|
2270 | Flattening is also performed on tuple types. |
---|
2271 | For example, the type ©[ int, [ int, int ], int ]© can be coerced, using flattening, into the type ©[ int, int, int, int ]©. |
---|
2272 | |
---|
2273 | A \newterm{structuring coercion} is the opposite of flattening; |
---|
2274 | a tuple is structured into a more complex nested tuple. |
---|
2275 | For 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 ]©. |
---|
2276 | In the following example, the last assignment illustrates all the tuple coercions: |
---|
2277 | \begin{cfa} |
---|
2278 | [ int, int, int, int ] w = [ 1, 2, 3, 4 ]; |
---|
2279 | int x = 5; |
---|
2280 | [ x, w ] = [ w, x ]; §\C{// all four tuple coercions}§ |
---|
2281 | \end{cfa} |
---|
2282 | Starting on the right-hand tuple in the last assignment statement, w is opened, producing a tuple of four values; |
---|
2283 | therefore, the right-hand tuple is now the tuple ©[ [ 1, 2, 3, 4 ], 5 ]©. |
---|
2284 | This 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. |
---|
2285 | The tuple ©[ 2, 3, 4, 5 ]© is then closed to create a tuple value. |
---|
2286 | Finally, ©x© is assigned ©1© and ©w© is assigned the tuple value using multiple assignment (see Section 14). |
---|
2287 | \begin{rationale} |
---|
2288 | A possible additional language extension is to use the structuring coercion for tuples to initialize a complex record with a tuple. |
---|
2289 | \end{rationale} |
---|
2290 | |
---|
2291 | |
---|
2292 | \section{Mass Assignment} |
---|
2293 | |
---|
2294 | \CFA permits assignment to several variables at once using mass assignment~\cite{CLU}. |
---|
2295 | Mass assignment has the following form: |
---|
2296 | \begin{cfa} |
---|
2297 | [ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = §\emph{expr}§; |
---|
2298 | \end{cfa} |
---|
2299 | \index{lvalue} |
---|
2300 | The left-hand side is a tuple of \emph{lvalues}, which is a list of expressions each yielding an address, \ie any data object that can appear on the left-hand side of a conventional assignment statement. |
---|
2301 | ©$\emph{expr}$© is any standard arithmetic expression. |
---|
2302 | Clearly, the types of the entities being assigned must be type compatible with the value of the expression. |
---|
2303 | |
---|
2304 | Mass assignment has parallel semantics, \eg the statement: |
---|
2305 | \begin{cfa} |
---|
2306 | [ x, y, z ] = 1.5; |
---|
2307 | \end{cfa} |
---|
2308 | is equivalent to: |
---|
2309 | \begin{cfa} |
---|
2310 | x = 1.5; y = 1.5; z = 1.5; |
---|
2311 | \end{cfa} |
---|
2312 | This semantics is not the same as the following in C: |
---|
2313 | \begin{cfa} |
---|
2314 | x = y = z = 1.5; |
---|
2315 | \end{cfa} |
---|
2316 | as conversions between intermediate assignments may lose information. |
---|
2317 | A more complex example is: |
---|
2318 | \begin{cfa} |
---|
2319 | [ i, y[i], z ] = a + b; |
---|
2320 | \end{cfa} |
---|
2321 | which is equivalent to: |
---|
2322 | \begin{cfa} |
---|
2323 | t = a + b; |
---|
2324 | a1 = &i; a2 = &y[i]; a3 = &z; |
---|
2325 | *a1 = t; *a2 = t; *a3 = t; |
---|
2326 | \end{cfa} |
---|
2327 | The temporary ©t© is necessary to store the value of the expression to eliminate conversion issues. |
---|
2328 | The temporaries for the addresses are needed so that locations on the left-hand side do not change as the values are assigned. |
---|
2329 | In this case, ©y[i]© uses the previous value of ©i© and not the new value set at the beginning of the mass assignment. |
---|
2330 | |
---|
2331 | |
---|
2332 | \section{Multiple Assignment} |
---|
2333 | |
---|
2334 | \CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}. |
---|
2335 | Multiple assignment has the following form: |
---|
2336 | \begin{cfa} |
---|
2337 | [ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = [ §\emph{expr}§, ... , §\emph{expr}§ ]; |
---|
2338 | \end{cfa} |
---|
2339 | \index{lvalue} |
---|
2340 | The left-hand side is a tuple of \emph{lvalues}, and the right-hand side is a tuple of \emph{expr}s. |
---|
2341 | Each \emph{expr} appearing on the right-hand 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. |
---|
2342 | An example of multiple assignment is: |
---|
2343 | \begin{cfa} |
---|
2344 | [ x, y, z ] = [ 1, 2, 3 ]; |
---|
2345 | \end{cfa} |
---|
2346 | Here, the values ©1©, ©2© and ©3© are assigned, respectively, to the variables ©x©, ©y© and ©z©. |
---|
2347 | A more complex example is: |
---|
2348 | \begin{cfa} |
---|
2349 | [ i, y[ i ], z ] = [ 1, i, a + b ]; |
---|
2350 | \end{cfa} |
---|
2351 | Here, the values ©1©, ©i© and ©a + b© are assigned to the variables ©i©, ©y[i]© and ©z©, respectively. |
---|
2352 | Note, the parallel semantics of |
---|
2353 | multiple assignment ensures: |
---|
2354 | \begin{cfa} |
---|
2355 | [ x, y ] = [ y, x ]; |
---|
2356 | \end{cfa} |
---|
2357 | correctly interchanges (swaps) the values stored in ©x© and ©y©. |
---|
2358 | The following cases are errors: |
---|
2359 | \begin{cfa} |
---|
2360 | [ a, b, c ] = [ 1, 2, 3, 4 ]; |
---|
2361 | [ a, b, c ] = [ 1, 2 ]; |
---|
2362 | \end{cfa} |
---|
2363 | because the number of entities in the left-hand tuple is unequal with the right-hand tuple. |
---|
2364 | |
---|
2365 | As 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; |
---|
2366 | both these examples produce indeterminate results: |
---|
2367 | \begin{cfa} |
---|
2368 | f( x++, x++ ); §\C{// C routine call with side effects in arguments}§ |
---|
2369 | [ v1, v2 ] = [ x++, x++ ]; §\C{// side effects in righthand side of multiple assignment}§ |
---|
2370 | \end{cfa} |
---|
2371 | |
---|
2372 | |
---|
2373 | \section{Cascade Assignment} |
---|
2374 | |
---|
2375 | As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment. |
---|
2376 | Cascade assignment has the following form: |
---|
2377 | \begin{cfa} |
---|
2378 | §\emph{tuple}§ = §\emph{tuple}§ = ... = §\emph{tuple}§; |
---|
2379 | \end{cfa} |
---|
2380 | and it has the same parallel semantics as for mass and multiple assignment. |
---|
2381 | Some examples of cascade assignment are: |
---|
2382 | \begin{cfa} |
---|
2383 | x1 = y1 = x2 = y2 = 0; |
---|
2384 | [ x1, y1 ] = [ x2, y2 ] = [ x3, y3 ]; |
---|
2385 | [ x1, y1 ] = [ x2, y2 ] = 0; |
---|
2386 | [ x1, y1 ] = z = 0; |
---|
2387 | \end{cfa} |
---|
2388 | As in C, the rightmost assignment is performed first, \ie assignment parses right to left. |
---|
2389 | |
---|
2390 | |
---|
2391 | \section{Field Tuples} |
---|
2392 | |
---|
2393 | Tuples may be used to select multiple fields of a record by field name. |
---|
2394 | Its general form is: |
---|
2395 | \begin{cfa} |
---|
2396 | §\emph{expr}§ . [ §\emph{fieldlist}§ ] |
---|
2397 | §\emph{expr}§ -> [ §\emph{fieldlist}§ ] |
---|
2398 | \end{cfa} |
---|
2399 | \emph{expr} is any expression yielding a value of type record, \eg ©struct©, ©union©. |
---|
2400 | Each element of \emph{ fieldlist} is an element of the record specified by \emph{expr}. |
---|
2401 | A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is |
---|
2402 | the following: |
---|
2403 | \begin{cfa} |
---|
2404 | struct s { |
---|
2405 | int f1, f2; |
---|
2406 | char f3; |
---|
2407 | double f4; |
---|
2408 | } v; |
---|
2409 | v.[ f3, f1, f2 ] = ['x', 11, 17 ]; §\C{// equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17}§ |
---|
2410 | f( v.[ f3, f1, f2 ] ); §\C{// equivalent to f( v.f3, v.f1, v.f2 )}§ |
---|
2411 | \end{cfa} |
---|
2412 | Note, the fields appearing in a record-field tuple may be specified in any order; |
---|
2413 | also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple. |
---|
2414 | |
---|
2415 | If 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: |
---|
2416 | \begin{cfa} |
---|
2417 | struct inner { |
---|
2418 | int f2, f3; |
---|
2419 | }; |
---|
2420 | struct outer { |
---|
2421 | int f1; |
---|
2422 | struct inner i; |
---|
2423 | double f4; |
---|
2424 | } o; |
---|
2425 | |
---|
2426 | o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ]; |
---|
2427 | \end{cfa} |
---|
2428 | |
---|
2429 | |
---|
2430 | \section{I/O Library} |
---|
2431 | \label{s:IOLibrary} |
---|
2432 | \index{input/output library} |
---|
2433 | |
---|
2434 | The goal of \CFA I/O is to simplify the common cases\index{I/O!common case}, while fully supporting polymorphism and user defined types in a consistent way. |
---|
2435 | The \CFA header file for the I/O library is \Indexc{fstream}. |
---|
2436 | |
---|
2437 | The common case is printing out a sequence of variables separated by whitespace. |
---|
2438 | \begin{quote2} |
---|
2439 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
2440 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{\CC}} \\ |
---|
2441 | \begin{cfa} |
---|
2442 | int x = 1, y = 2, z = 3; |
---|
2443 | sout | x ®|® y ®|® z | endl; |
---|
2444 | \end{cfa} |
---|
2445 | & |
---|
2446 | \begin{cfa} |
---|
2447 | |
---|
2448 | cout << x ®<< " "® << y ®<< " "® << z << endl; |
---|
2449 | \end{cfa} |
---|
2450 | \\ |
---|
2451 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2452 | 1® ®2® ®3 |
---|
2453 | \end{cfa} |
---|
2454 | & |
---|
2455 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2456 | 1 2 3 |
---|
2457 | \end{cfa} |
---|
2458 | \end{tabular} |
---|
2459 | \end{quote2} |
---|
2460 | The \CFA form has half as many characters as the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators. |
---|
2461 | Similar simplification occurs for \Index{tuple} I/O, which prints all a tuple's values, each separated by ``\lstinline[showspaces=true]@, @''. |
---|
2462 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2463 | [int, int] t1 = [1, 2], t2 = [3, 4]; |
---|
2464 | sout | t1 | t2 | endl; §\C{// print tuples}§ |
---|
2465 | \end{cfa} |
---|
2466 | \begin{cfa}[mathescape=off,showspaces=true,belowskip=0pt] |
---|
2467 | 1®, ®2®, ®3®, ®4 |
---|
2468 | \end{cfa} |
---|
2469 | Finally, \CFA uses the logical-or operator for I/O because it is the lowest-priority overloadable operator, other than assignment. |
---|
2470 | Therefore, fewer output expressions require parenthesis. |
---|
2471 | \begin{quote2} |
---|
2472 | \begin{tabular}{@{}ll@{}} |
---|
2473 | \textbf{\CFA:} |
---|
2474 | & |
---|
2475 | \begin{cfa} |
---|
2476 | sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl; |
---|
2477 | \end{cfa} |
---|
2478 | \\ |
---|
2479 | \textbf{\CC:} |
---|
2480 | & |
---|
2481 | \begin{cfa} |
---|
2482 | cout << x * 3 << y + 1 << ®(®z << 2®)® << ®(®x == y®)® << (x | y) << (x || y) << (x > z ? 1 : 2) << endl; |
---|
2483 | \end{cfa} |
---|
2484 | \\ |
---|
2485 | & |
---|
2486 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2487 | 3 3 12 0 3 1 2 |
---|
2488 | \end{cfa} |
---|
2489 | \end{tabular} |
---|
2490 | \end{quote2} |
---|
2491 | There is a weak similarity between the \CFA logical-or operator and the Shell pipe-operator for moving data, where data flows in the correct direction for input but the opposite direction for output. |
---|
2492 | |
---|
2493 | |
---|
2494 | \subsection{Implicit Separator} |
---|
2495 | |
---|
2496 | The \Index{implicit separator}\index{I/O!separator} character (space/blank) is a separator not a terminator. |
---|
2497 | The rules for implicitly adding the separator are: |
---|
2498 | \begin{enumerate} |
---|
2499 | \item |
---|
2500 | A separator does not appear at the start or end of a line. |
---|
2501 | \begin{cfa}[belowskip=0pt] |
---|
2502 | sout | 1 | 2 | 3 | endl; |
---|
2503 | \end{cfa} |
---|
2504 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2505 | 1 2 3 |
---|
2506 | \end{cfa} |
---|
2507 | |
---|
2508 | \item |
---|
2509 | A separator does not appear before or after a character literal or variable. |
---|
2510 | \begin{cfa} |
---|
2511 | sout | '1' | '2' | '3' | endl; |
---|
2512 | 123 |
---|
2513 | \end{cfa} |
---|
2514 | |
---|
2515 | \item |
---|
2516 | A separator does not appear before or after a null (empty) C string. |
---|
2517 | \begin{cfa} |
---|
2518 | sout | 1 | "" | 2 | "" | 3 | endl; |
---|
2519 | 123 |
---|
2520 | \end{cfa} |
---|
2521 | which is a local mechanism to disable insertion of the separator character. |
---|
2522 | |
---|
2523 | \item |
---|
2524 | A separator does not appear before a C string starting with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[mathescape=off,basicstyle=\tt]@([{=$£¥¡¿«@ |
---|
2525 | %$ |
---|
2526 | \begin{cfa}[mathescape=off] |
---|
2527 | sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x £" | 6 | "x ¥" |
---|
2528 | | 7 | "x ¡" | 8 | "x ¿" | 9 | "x «" | 10 | endl; |
---|
2529 | \end{cfa} |
---|
2530 | %$ |
---|
2531 | \begin{cfa}[mathescape=off,basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2532 | x ®(®1 x ®[®2 x ®{®3 x ®=®4 x ®$®5 x ®£®6 x ®¥®7 x ®¡®8 x ®¿®9 x ®«®10 |
---|
2533 | \end{cfa} |
---|
2534 | %$ |
---|
2535 | where \lstinline[basicstyle=\tt]@¡¿@ are inverted opening exclamation and question marks, and \lstinline[basicstyle=\tt]@«@ is an opening citation mark. |
---|
2536 | |
---|
2537 | \item |
---|
2538 | {\lstset{language=CFA,deletedelim=**[is][]{¢}{¢}} |
---|
2539 | A seperator does not appear after a C string ending with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[basicstyle=\tt]@,.;!?)]}%¢»@ |
---|
2540 | \begin{cfa}[belowskip=0pt] |
---|
2541 | sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x" |
---|
2542 | | 7 | "¢ x" | 8 | "» x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl; |
---|
2543 | \end{cfa} |
---|
2544 | \begin{cfa}[basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2545 | 1®,® x 2®.® x 3®;® x 4®!® x 5®?® x 6®%® x 7§\color{red}\textcent§ x 8®»® x 9®)® x 10®]® x 11®}® x |
---|
2546 | \end{cfa}}% |
---|
2547 | where \lstinline[basicstyle=\tt]@»@ is a closing citation mark. |
---|
2548 | |
---|
2549 | \item |
---|
2550 | A seperator does not appear before or after a C string begining/ending with the \Index*{ASCII} quote or whitespace characters: \lstinline[basicstyle=\tt,showspaces=true]@`'": \t\v\f\r\n@ |
---|
2551 | \begin{cfa}[belowskip=0pt] |
---|
2552 | sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl; |
---|
2553 | \end{cfa} |
---|
2554 | \begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt] |
---|
2555 | x®`®1®`®x§\color{red}\texttt{'}§2§\color{red}\texttt{'}§x§\color{red}\texttt{"}§3§\color{red}\texttt{"}§x®:®4®:®x® ®5® ®x® ®6® ®x |
---|
2556 | \end{cfa} |
---|
2557 | |
---|
2558 | \item |
---|
2559 | If a space is desired before or after one of the special string start/end characters, simply insert a space. |
---|
2560 | \begin{cfa}[belowskip=0pt] |
---|
2561 | sout | "x (§\color{red}\texttt{\textvisiblespace}§" | 1 | "§\color{red}\texttt{\textvisiblespace}§) x" | 2 | "§\color{red}\texttt{\textvisiblespace}§, x" | 3 | "§\color{red}\texttt{\textvisiblespace}§:x:§\color{red}\texttt{\textvisiblespace}§" | 4 | endl; |
---|
2562 | \end{cfa} |
---|
2563 | \begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt] |
---|
2564 | x (® ®1® ®) x 2® ®, x 3® ®:x:® ®4 |
---|
2565 | \end{cfa} |
---|
2566 | \end{enumerate} |
---|
2567 | |
---|
2568 | |
---|
2569 | \subsection{Manipulator} |
---|
2570 | |
---|
2571 | The following routines and \CC-style \Index{manipulator}s control implicit seperation. |
---|
2572 | \begin{enumerate} |
---|
2573 | \item |
---|
2574 | Routines \Indexc{sepSet}\index{manipulator!sepSet@©sepSet©} and \Indexc{sepGet}\index{manipulator!sepGet@©sepGet©} set and get the separator string. |
---|
2575 | The separator string can be at most 16 characters including the ©'\0'© string terminator (15 printable characters). |
---|
2576 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2577 | sepSet( sout, ", $" ); §\C{// set separator from " " to ", \$"}§ |
---|
2578 | sout | 1 | 2 | 3 | " \"" | ®sepGet( sout )® | "\"" | endl; |
---|
2579 | \end{cfa} |
---|
2580 | %$ |
---|
2581 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt] |
---|
2582 | 1®, $®2®, $®3 ®", $"® |
---|
2583 | \end{cfa} |
---|
2584 | %$ |
---|
2585 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2586 | sepSet( sout, " " ); §\C{// reset separator to " "}§ |
---|
2587 | sout | 1 | 2 | 3 | " \"" | ®sepGet( sout )® | "\"" | endl; |
---|
2588 | \end{cfa} |
---|
2589 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt] |
---|
2590 | 1® ®2® ®3 ®" "® |
---|
2591 | \end{cfa} |
---|
2592 | |
---|
2593 | \item |
---|
2594 | Routine \Indexc{sepSetTuple}\index{manipulator!sepSetTuple@©sepSetTuple©} and \Indexc{sepGetTuple}\index{manipulator!sepGetTuple@©sepGetTuple©} get and set the tuple separator-string. |
---|
2595 | The tuple separator-string can be at most 16 characters including the ©'\0'© string terminator (15 printable characters). |
---|
2596 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2597 | sepSetTuple( sout, " " ); §\C{// set tuple separator from ", " to " "}§ |
---|
2598 | sout | t1 | t2 | " \"" | ®sepGetTuple( sout )® | "\"" | endl; |
---|
2599 | \end{cfa} |
---|
2600 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt] |
---|
2601 | 1 2 3 4 ®" "® |
---|
2602 | \end{cfa} |
---|
2603 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2604 | sepSetTuple( sout, ", " ); §\C{// reset tuple separator to ", "}§ |
---|
2605 | sout | t1 | t2 | " \"" | ®sepGetTuple( sout )® | "\"" | endl; |
---|
2606 | \end{cfa} |
---|
2607 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt] |
---|
2608 | 1, 2, 3, 4 ®", "® |
---|
2609 | \end{cfa} |
---|
2610 | |
---|
2611 | \item |
---|
2612 | Manipulators \Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} \emph{locally} toggle printing the separator, \ie the seperator is adjusted only with respect to the next printed item. |
---|
2613 | \begin{cfa}[mathescape=off,belowskip=0pt] |
---|
2614 | sout | sepOn | 1 | 2 | 3 | sepOn | endl; §\C{// separator at start/end of line}§ |
---|
2615 | \end{cfa} |
---|
2616 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2617 | ® ®1 2 3® ® |
---|
2618 | \end{cfa} |
---|
2619 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2620 | sout | 1 | sepOff | 2 | 3 | endl; §\C{// locally turn off implicit separator}§ |
---|
2621 | \end{cfa} |
---|
2622 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2623 | 12 3 |
---|
2624 | \end{cfa} |
---|
2625 | The tuple separator also responses to being turned on and off. |
---|
2626 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2627 | sout | sepOn | t1 | sepOff | t2 | endl; §\C{// locally turn on/off implicit separation}§ |
---|
2628 | \end{cfa} |
---|
2629 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2630 | , 1, 23, 4 |
---|
2631 | \end{cfa} |
---|
2632 | Notice a tuple seperator starts the line because the next item is a tuple. |
---|
2633 | |
---|
2634 | \item |
---|
2635 | Manipulators \Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} \emph{globally} toggle printing the separator, \ie the seperator is adjusted with respect to all subsequent printed items, unless locally adjusted. |
---|
2636 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2637 | sout | sepDisable | 1 | 2 | 3 | endl; §\C{// globally turn off implicit separation}§ |
---|
2638 | \end{cfa} |
---|
2639 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2640 | 123 |
---|
2641 | \end{cfa} |
---|
2642 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2643 | sout | 1 | ®sepOn® | 2 | 3 | endl; §\C{// locally turn on implicit separator}§ |
---|
2644 | \end{cfa} |
---|
2645 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2646 | 1® ®23 |
---|
2647 | \end{cfa} |
---|
2648 | \begin{cfa}[mathescape=off,aboveskip=0pt,belowskip=0pt] |
---|
2649 | sout | sepEnable | 1 | 2 | 3 | endl; §\C{// globally turn on implicit separation}§ |
---|
2650 | \end{cfa} |
---|
2651 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2652 | 1 2 3 |
---|
2653 | \end{cfa} |
---|
2654 | \end{enumerate} |
---|
2655 | |
---|
2656 | \begin{comment} |
---|
2657 | #include <fstream> |
---|
2658 | |
---|
2659 | int main( void ) { |
---|
2660 | int x = 1, y = 2, z = 3; |
---|
2661 | sout | x | y | z | endl; |
---|
2662 | [int, int] t1 = [1, 2], t2 = [3, 4]; |
---|
2663 | sout | t1 | t2 | endl; // print tuple |
---|
2664 | sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl; |
---|
2665 | sout | 1 | 2 | 3 | endl; |
---|
2666 | sout | '1' | '2' | '3' | endl; |
---|
2667 | sout | 1 | "" | 2 | "" | 3 | endl; |
---|
2668 | sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x £" | 6 | "x ¥" |
---|
2669 | | 7 | "x ¡" | 8 | "x ¿" | 9 | "x «" | 10 | endl; |
---|
2670 | sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x" |
---|
2671 | | 7 | "¢ x" | 8 | "» x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl; |
---|
2672 | sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl; |
---|
2673 | sout | "x ( " | 1 | " ) x" | 2 | " , x" | 3 | " :x: " | 4 | endl; |
---|
2674 | |
---|
2675 | sepSet( sout, ", $" ); // set separator from " " to ", $" |
---|
2676 | sout | 1 | 2 | 3 | " \"" | sepGet( sout ) | "\"" | endl; |
---|
2677 | sepSet( sout, " " ); // reset separator to " " |
---|
2678 | sout | 1 | 2 | 3 | " \"" | sepGet( sout ) | "\"" | endl; |
---|
2679 | |
---|
2680 | sout | sepOn | 1 | 2 | 3 | sepOn | endl; // separator at start of line |
---|
2681 | sout | 1 | sepOff | 2 | 3 | endl; // locally turn off implicit separator |
---|
2682 | |
---|
2683 | sout | sepDisable | 1 | 2 | 3 | endl; // globally turn off implicit separation |
---|
2684 | sout | 1 | sepOn | 2 | 3 | endl; // locally turn on implicit separator |
---|
2685 | sout | sepEnable | 1 | 2 | 3 | endl; // globally turn on implicit separation |
---|
2686 | |
---|
2687 | sepSetTuple( sout, " " ); // set tuple separator from ", " to " " |
---|
2688 | sout | t1 | t2 | " \"" | sepGetTuple( sout ) | "\"" | endl; |
---|
2689 | sepSetTuple( sout, ", " ); // reset tuple separator to ", " |
---|
2690 | sout | t1 | t2 | " \"" | sepGetTuple( sout ) | "\"" | endl; |
---|
2691 | |
---|
2692 | sout | t1 | t2 | endl; // print tuple |
---|
2693 | sout | sepOn | t1 | sepOff | t2 | endl; // locally turn on/off implicit separation |
---|
2694 | } |
---|
2695 | |
---|
2696 | // Local Variables: // |
---|
2697 | // tab-width: 4 // |
---|
2698 | // fill-column: 100 // |
---|
2699 | // End: // |
---|
2700 | \end{comment} |
---|
2701 | %$ |
---|
2702 | |
---|
2703 | |
---|
2704 | \section{Types} |
---|
2705 | |
---|
2706 | \subsection{Type Definitions} |
---|
2707 | |
---|
2708 | \CFA allows users to define new types using the keyword type. |
---|
2709 | |
---|
2710 | \begin{cfa} |
---|
2711 | // SensorValue is a distinct type and represented as an int |
---|
2712 | type SensorValue = int; |
---|
2713 | \end{cfa} |
---|
2714 | |
---|
2715 | A 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. |
---|
2716 | This means that users can define distinct function overloads for the new type (see Overloading for more information). |
---|
2717 | For example: |
---|
2718 | |
---|
2719 | \begin{cfa} |
---|
2720 | type SensorValue = int; |
---|
2721 | void printValue(int v) {...} |
---|
2722 | void printValue(SensorValue v) {...} |
---|
2723 | void process(int v) {...} |
---|
2724 | |
---|
2725 | SensorValue s = ...; |
---|
2726 | |
---|
2727 | printValue(s); // calls version with SensorValue argument |
---|
2728 | |
---|
2729 | printValue((int) s); // calls version with int argument |
---|
2730 | |
---|
2731 | process(s); // implicit conversion to int |
---|
2732 | \end{cfa} |
---|
2733 | |
---|
2734 | If SensorValue was defined with a typedef, then these two print functions would not have unique signatures. |
---|
2735 | This can be very useful to create a distinct type that has the same representation as another type. |
---|
2736 | |
---|
2737 | The compiler will assume it can safely convert from the old type to the new type, implicitly. |
---|
2738 | Users may override this and define a function that must be called to convert from one type to another. |
---|
2739 | |
---|
2740 | \begin{cfa} |
---|
2741 | type SensorValue = int; |
---|
2742 | // ()? is the overloaded conversion operator identifier |
---|
2743 | // This function converts an int to a SensorValue |
---|
2744 | SensorValue ()?(int val) { |
---|
2745 | ... |
---|
2746 | } |
---|
2747 | void process(int v) {...} |
---|
2748 | |
---|
2749 | SensorValue s = ...; |
---|
2750 | process(s); // implicit call to conversion operator |
---|
2751 | \end{cfa} |
---|
2752 | |
---|
2753 | In many cases, it is not desired for the compiler to do this implicit conversion. |
---|
2754 | To avoid that, the user can use the explicit modifier on the conversion operator. |
---|
2755 | Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error. |
---|
2756 | |
---|
2757 | \begin{cfa} |
---|
2758 | type SensorValue = int; |
---|
2759 | |
---|
2760 | // conversion from int to SensorValue; must be explicit |
---|
2761 | explicit SensorValue ()?(int val) { |
---|
2762 | ... |
---|
2763 | } |
---|
2764 | |
---|
2765 | void process(int v) {...} |
---|
2766 | |
---|
2767 | SensorValue s = ...; |
---|
2768 | process(s); // implicit cast to int: compile-time error |
---|
2769 | process((int) s); // explicit cast to int: calls conversion func |
---|
2770 | \end{cfa} |
---|
2771 | |
---|
2772 | The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to: |
---|
2773 | \begin{cfa} |
---|
2774 | type SensorValue = int; |
---|
2775 | explicit SensorValue ()?(int); |
---|
2776 | void process(int v) {...} |
---|
2777 | |
---|
2778 | SensorValue s = ...; |
---|
2779 | process(s); // compile-time error |
---|
2780 | process((int) s); // type is converted, no function is called |
---|
2781 | \end{cfa} |
---|
2782 | |
---|
2783 | |
---|
2784 | \subsection{Structures} |
---|
2785 | |
---|
2786 | Structures in \CFA are basically the same as structures in C. |
---|
2787 | A structure is defined with the same syntax as in C. |
---|
2788 | When referring to a structure in \CFA, users may omit the struct keyword. |
---|
2789 | \begin{cfa} |
---|
2790 | struct Point { |
---|
2791 | double x; |
---|
2792 | double y; |
---|
2793 | }; |
---|
2794 | |
---|
2795 | Point p = {0.0, 0.0}; |
---|
2796 | \end{cfa} |
---|
2797 | |
---|
2798 | \CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields. |
---|
2799 | Composition is achieved by embedding one type into another. |
---|
2800 | When 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. |
---|
2801 | Embedding types is achieved using anonymous members. |
---|
2802 | For example, using Point from above: |
---|
2803 | \begin{cfa} |
---|
2804 | void foo(Point p); |
---|
2805 | |
---|
2806 | struct ColoredPoint { |
---|
2807 | Point; // anonymous member (no identifier) |
---|
2808 | int Color; |
---|
2809 | }; |
---|
2810 | ... |
---|
2811 | ColoredPoint cp = ...; |
---|
2812 | cp.x = 10.3; // x from Point is accessed directly |
---|
2813 | cp.color = 0x33aaff; // color is accessed normally |
---|
2814 | foo(cp); // cp can be used directly as a Point |
---|
2815 | \end{cfa} |
---|
2816 | |
---|
2817 | |
---|
2818 | \section{Constructors and Destructors} |
---|
2819 | |
---|
2820 | \CFA supports C initialization of structures, but it also adds constructors for more advanced initialization. |
---|
2821 | Additionally, \CFA adds destructors that are called when a variable is deallocated (variable goes out of scope or object is deleted). |
---|
2822 | These functions take a reference to the structure as a parameter (see References for more information). |
---|
2823 | |
---|
2824 | \begin{figure} |
---|
2825 | \begin{cfa} |
---|
2826 | struct Widget { |
---|
2827 | int id; |
---|
2828 | float size; |
---|
2829 | Parts *optionalParts; |
---|
2830 | }; |
---|
2831 | |
---|
2832 | // ?{} is the constructor operator identifier |
---|
2833 | // The first argument is a reference to the type to initialize |
---|
2834 | // Subsequent arguments can be specified for initialization |
---|
2835 | |
---|
2836 | void ?{}(Widget &w) { // default constructor |
---|
2837 | w.id = -1; |
---|
2838 | w.size = 0.0; |
---|
2839 | w.optionalParts = 0; |
---|
2840 | } |
---|
2841 | |
---|
2842 | // constructor with values (does not need to include all fields) |
---|
2843 | void ?{}(Widget &w, int id, float size) { |
---|
2844 | w.id = id; |
---|
2845 | w.size = size; |
---|
2846 | w.optionalParts = 0; |
---|
2847 | } |
---|
2848 | |
---|
2849 | // ^? is the destructor operator identifier |
---|
2850 | void ^?(Widget &w) { // destructor |
---|
2851 | w.id = 0; |
---|
2852 | w.size = 0.0; |
---|
2853 | if (w.optionalParts != 0) { |
---|
2854 | // This is the only pointer to optionalParts, free it |
---|
2855 | free(w.optionalParts); |
---|
2856 | w.optionalParts = 0; |
---|
2857 | } |
---|
2858 | } |
---|
2859 | |
---|
2860 | Widget baz; // reserve space only |
---|
2861 | Widget foo{}; // calls default constructor |
---|
2862 | Widget bar{23, 2.45}; // calls constructor with values |
---|
2863 | baz{24, 0.91}; // calls constructor with values |
---|
2864 | ?{}(baz, 24, 0.91}; // explicit call to constructor |
---|
2865 | ^bar; // explicit call to destructor |
---|
2866 | ^?(bar); // explicit call to destructor |
---|
2867 | \end{cfa} |
---|
2868 | \caption{Constructors and Destructors} |
---|
2869 | \end{figure} |
---|
2870 | |
---|
2871 | |
---|
2872 | \section{Overloading} |
---|
2873 | |
---|
2874 | Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name. |
---|
2875 | In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C. |
---|
2876 | This may cause identical C and \CFA programs to behave differently. |
---|
2877 | The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used. |
---|
2878 | Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users. |
---|
2879 | Disadvantages 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. |
---|
2880 | \CFA allows overloading of functions, operators, variables, and even the constants 0 and 1. |
---|
2881 | |
---|
2882 | The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads. |
---|
2883 | The best valid interpretations are the valid interpretations that use the fewest unsafe conversions. |
---|
2884 | Of these, the best are those where the functions and objects involved are the least polymorphic. |
---|
2885 | Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions. |
---|
2886 | Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions. |
---|
2887 | If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous. |
---|
2888 | For details about type inference and overload resolution, please see the \CFA Language Specification. |
---|
2889 | \begin{cfa} |
---|
2890 | int foo(int a, int b) { |
---|
2891 | float sum = 0.0; |
---|
2892 | float special = 1.0; |
---|
2893 | { |
---|
2894 | int sum = 0; |
---|
2895 | // both the float and int versions of sum are available |
---|
2896 | float special = 4.0; |
---|
2897 | // this inner special hides the outer version |
---|
2898 | ... |
---|
2899 | } |
---|
2900 | ... |
---|
2901 | } |
---|
2902 | \end{cfa} |
---|
2903 | |
---|
2904 | |
---|
2905 | \subsection{Overloaded Constant} |
---|
2906 | |
---|
2907 | The constants 0 and 1 have special meaning. |
---|
2908 | In \CFA, as in C, all scalar types can be incremented and |
---|
2909 | decremented, which is defined in terms of adding or subtracting 1. |
---|
2910 | The 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)©). |
---|
2911 | |
---|
2912 | In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a special case. |
---|
2913 | However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their polymorphic parameters, and user-defined pointer-like types may need a null value. |
---|
2914 | Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©. |
---|
2915 | |
---|
2916 | Why just 0 and 1? Why not other integers? No other integers have special status in C. |
---|
2917 | A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement. |
---|
2918 | Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed. |
---|
2919 | The complexity of such a feature does not seem worth the gain. |
---|
2920 | |
---|
2921 | For example, to define the constants for a complex type, the programmer would define the following: |
---|
2922 | |
---|
2923 | \begin{cfa} |
---|
2924 | struct Complex { |
---|
2925 | double real; |
---|
2926 | double imaginary; |
---|
2927 | } |
---|
2928 | |
---|
2929 | const Complex 0 = {0, 0}; |
---|
2930 | const Complex 1 = {1, 0}; |
---|
2931 | ... |
---|
2932 | |
---|
2933 | Complex a = 0; |
---|
2934 | ... |
---|
2935 | |
---|
2936 | a++; |
---|
2937 | ... |
---|
2938 | if (a) { // same as if (a == 0) |
---|
2939 | ... |
---|
2940 | } |
---|
2941 | \end{cfa} |
---|
2942 | |
---|
2943 | |
---|
2944 | \subsection{Variable Overloading} |
---|
2945 | |
---|
2946 | The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types. |
---|
2947 | Allowing 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. |
---|
2948 | For example, a developer may want to do the following: |
---|
2949 | \begin{cfa} |
---|
2950 | int pi = 3; |
---|
2951 | float pi = 3.14; |
---|
2952 | char pi = .p.; |
---|
2953 | \end{cfa} |
---|
2954 | |
---|
2955 | |
---|
2956 | \subsection{Function Overloading} |
---|
2957 | |
---|
2958 | Overloaded 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). |
---|
2959 | |
---|
2960 | The examples below give some basic intuition about how the resolution works. |
---|
2961 | \begin{cfa} |
---|
2962 | // Choose the one with less conversions |
---|
2963 | int doSomething(int value) {...} // option 1 |
---|
2964 | int doSomething(short value) {...} // option 2 |
---|
2965 | |
---|
2966 | int a, b = 4; |
---|
2967 | short c = 2; |
---|
2968 | |
---|
2969 | a = doSomething(b); // chooses option 1 |
---|
2970 | a = doSomething(c); // chooses option 2 |
---|
2971 | |
---|
2972 | // Choose the specialized version over the generic |
---|
2973 | |
---|
2974 | generic(type T) |
---|
2975 | T bar(T rhs, T lhs) {...} // option 3 |
---|
2976 | float bar(float rhs, float lhs){...} // option 4 |
---|
2977 | float a, b, c; |
---|
2978 | double d, e, f; |
---|
2979 | c = bar(a, b); // chooses option 4 |
---|
2980 | |
---|
2981 | // specialization is preferred over unsafe conversions |
---|
2982 | |
---|
2983 | f = bar(d, e); // chooses option 5 |
---|
2984 | \end{cfa} |
---|
2985 | |
---|
2986 | |
---|
2987 | \subsection{Operator Overloading} |
---|
2988 | |
---|
2989 | \CFA also allows operators to be overloaded, to simplify the use of user-defined types. |
---|
2990 | Overloading 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. |
---|
2991 | \CFA uses the following special identifiers to name overloaded operators: |
---|
2992 | |
---|
2993 | \begin{table}[hbt] |
---|
2994 | \hfil |
---|
2995 | \begin{tabular}[t]{ll} |
---|
2996 | %identifier & operation \\ \hline |
---|
2997 | ©?[?]© & subscripting \impl{?[?]}\\ |
---|
2998 | ©?()© & function call \impl{?()}\\ |
---|
2999 | ©?++© & postfix increment \impl{?++}\\ |
---|
3000 | ©?--© & postfix decrement \impl{?--}\\ |
---|
3001 | ©++?© & prefix increment \impl{++?}\\ |
---|
3002 | ©--?© & prefix decrement \impl{--?}\\ |
---|
3003 | ©*?© & dereference \impl{*?}\\ |
---|
3004 | ©+?© & unary plus \impl{+?}\\ |
---|
3005 | ©-?© & arithmetic negation \impl{-?}\\ |
---|
3006 | ©~?© & bitwise negation \impl{~?}\\ |
---|
3007 | ©!?© & logical complement \impl{"!?}\\ |
---|
3008 | ©?*?© & multiplication \impl{?*?}\\ |
---|
3009 | ©?/?© & division \impl{?/?}\\ |
---|
3010 | \end{tabular}\hfil |
---|
3011 | \begin{tabular}[t]{ll} |
---|
3012 | %identifier & operation \\ \hline |
---|
3013 | ©?%?© & remainder \impl{?%?}\\ |
---|
3014 | ©?+?© & addition \impl{?+?}\\ |
---|
3015 | ©?-?© & subtraction \impl{?-?}\\ |
---|
3016 | ©?<<?© & left shift \impl{?<<?}\\ |
---|
3017 | ©?>>?© & right shift \impl{?>>?}\\ |
---|
3018 | ©?<?© & less than \impl{?<?}\\ |
---|
3019 | ©?<=?© & less than or equal \impl{?<=?}\\ |
---|
3020 | ©?>=?© & greater than or equal \impl{?>=?}\\ |
---|
3021 | ©?>?© & greater than \impl{?>?}\\ |
---|
3022 | ©?==?© & equality \impl{?==?}\\ |
---|
3023 | ©?!=?© & inequality \impl{?"!=?}\\ |
---|
3024 | ©?&?© & bitwise AND \impl{?&?}\\ |
---|
3025 | \end{tabular}\hfil |
---|
3026 | \begin{tabular}[t]{ll} |
---|
3027 | %identifier & operation \\ \hline |
---|
3028 | ©?^?© & exclusive OR \impl{?^?}\\ |
---|
3029 | ©?|?© & inclusive OR \impl{?"|?}\\ |
---|
3030 | ©?=?© & simple assignment \impl{?=?}\\ |
---|
3031 | ©?*=?© & multiplication assignment \impl{?*=?}\\ |
---|
3032 | ©?/=?© & division assignment \impl{?/=?}\\ |
---|
3033 | ©?%=?© & remainder assignment \impl{?%=?}\\ |
---|
3034 | ©?+=?© & addition assignment \impl{?+=?}\\ |
---|
3035 | ©?-=?© & subtraction assignment \impl{?-=?}\\ |
---|
3036 | ©?<<=?© & left-shift assignment \impl{?<<=?}\\ |
---|
3037 | ©?>>=?© & right-shift assignment \impl{?>>=?}\\ |
---|
3038 | ©?&=?© & bitwise AND assignment \impl{?&=?}\\ |
---|
3039 | ©?^=?© & exclusive OR assignment \impl{?^=?}\\ |
---|
3040 | ©?|=?© & inclusive OR assignment \impl{?"|=?}\\ |
---|
3041 | \end{tabular} |
---|
3042 | \hfil |
---|
3043 | \caption{Operator Identifiers} |
---|
3044 | \label{opids} |
---|
3045 | \end{table} |
---|
3046 | |
---|
3047 | These identifiers are defined such that the question marks in the name identify the location of the operands. |
---|
3048 | These operands represent the parameters to the functions, and define how the operands are mapped to the function call. |
---|
3049 | For example, ©a + b© becomes ©?+?(a, b)©. |
---|
3050 | |
---|
3051 | In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator. |
---|
3052 | These operators are called using the normal C syntax. |
---|
3053 | |
---|
3054 | \begin{cfa} |
---|
3055 | type Complex = struct { // define a Complex type |
---|
3056 | double real; |
---|
3057 | double imag; |
---|
3058 | } |
---|
3059 | |
---|
3060 | // Constructor with default values |
---|
3061 | |
---|
3062 | void ?{}(Complex &c, double real = 0.0, double imag = 0.0) { |
---|
3063 | c.real = real; |
---|
3064 | c.imag = imag; |
---|
3065 | } |
---|
3066 | |
---|
3067 | Complex ?+?(Complex lhs, Complex rhs) { |
---|
3068 | Complex sum; |
---|
3069 | sum.real = lhs.real + rhs.real; |
---|
3070 | sum.imag = lhs.imag + rhs.imag; |
---|
3071 | return sum; |
---|
3072 | } |
---|
3073 | |
---|
3074 | String ()?(const Complex c) { |
---|
3075 | // use the string conversions for the structure members |
---|
3076 | return (String)c.real + . + . + (String)c.imag + .i.; |
---|
3077 | } |
---|
3078 | ... |
---|
3079 | |
---|
3080 | Complex a, b, c = {1.0}; // constructor for c w/ default imag |
---|
3081 | ... |
---|
3082 | c = a + b; |
---|
3083 | print(.sum = . + c); |
---|
3084 | \end{cfa} |
---|
3085 | |
---|
3086 | |
---|
3087 | \section{Auto Type-Inferencing} |
---|
3088 | |
---|
3089 | Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type. |
---|
3090 | \begin{quote2} |
---|
3091 | \begin{tabular}{@{}l@{\hspace{3em}}ll@{}} |
---|
3092 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\Indexc{gcc}}} \\ |
---|
3093 | \begin{cfa} |
---|
3094 | |
---|
3095 | auto j = 3.0 * 4; |
---|
3096 | int i; |
---|
3097 | auto k = i; |
---|
3098 | \end{cfa} |
---|
3099 | & |
---|
3100 | \begin{cfa} |
---|
3101 | #define expr 3.0 * i |
---|
3102 | typeof(expr) j = expr; |
---|
3103 | int i; |
---|
3104 | typeof(i) k = i; |
---|
3105 | \end{cfa} |
---|
3106 | & |
---|
3107 | \begin{cfa} |
---|
3108 | |
---|
3109 | // use type of initialization expression |
---|
3110 | |
---|
3111 | // use type of primary variable |
---|
3112 | \end{cfa} |
---|
3113 | \end{tabular} |
---|
3114 | \end{quote2} |
---|
3115 | The two important capabilities are: |
---|
3116 | \begin{itemize} |
---|
3117 | \item |
---|
3118 | preventing having to determine or write out long generic types, |
---|
3119 | \item |
---|
3120 | ensure secondary variables, related to a primary variable, always have the same type. |
---|
3121 | \end{itemize} |
---|
3122 | |
---|
3123 | In \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. |
---|
3124 | \Indexc{gcc} provides ©typeof© to declare a secondary variable from a primary variable. |
---|
3125 | \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. |
---|
3126 | Only for overloaded routines with the same return type is variable type-inferencing possible. |
---|
3127 | Finally, ©auto© presents the programming problem of tracking down a type when the type is actually needed. |
---|
3128 | For example, given |
---|
3129 | \begin{cfa} |
---|
3130 | auto j = ®...® |
---|
3131 | \end{cfa} |
---|
3132 | and the need to write a routine to compute using ©j© |
---|
3133 | \begin{cfa} |
---|
3134 | void rtn( ®...® parm ); |
---|
3135 | rtn( j ); |
---|
3136 | \end{cfa} |
---|
3137 | A programmer must work backwards to determine the type of ©j©'s initialization expression, reconstructing the possibly long generic type-name. |
---|
3138 | In this situation, having the type name or a short alias is very useful. |
---|
3139 | |
---|
3140 | There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type. |
---|
3141 | That is, when is the type of the variable more important than the type of its initialization expression. |
---|
3142 | For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors. |
---|
3143 | At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes. |
---|
3144 | |
---|
3145 | Given ©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. |
---|
3146 | Should a significant need arise, this feature can be revisited. |
---|
3147 | |
---|
3148 | |
---|
3149 | \begin{comment} |
---|
3150 | \section{Generics} |
---|
3151 | |
---|
3152 | \CFA supports parametric polymorphism to allow users to define generic functions and types. |
---|
3153 | Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types. |
---|
3154 | The type parameters can be restricted to satisfy a set of constraints. |
---|
3155 | This enables \CFA to build fully compiled generic functions and types, unlike other languages like \Index*[C++]{\CC{}} where templates are expanded or must be explicitly instantiated. |
---|
3156 | |
---|
3157 | |
---|
3158 | \subsection{Generic Functions} |
---|
3159 | |
---|
3160 | Generic functions in \CFA are similar to template functions in \Index*[C++]{\CC{}}, and will sometimes be expanded into specialized versions, just like in \CC. |
---|
3161 | The 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. |
---|
3162 | This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically). |
---|
3163 | Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated. |
---|
3164 | |
---|
3165 | A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this: |
---|
3166 | |
---|
3167 | \begin{cfa} |
---|
3168 | generic(type T) |
---|
3169 | void swap(T &a, T &b) { |
---|
3170 | T tmp = a; |
---|
3171 | a = b; |
---|
3172 | b = a; |
---|
3173 | } |
---|
3174 | |
---|
3175 | int a, b; |
---|
3176 | swap(a, b); |
---|
3177 | |
---|
3178 | Point p1, p2; |
---|
3179 | swap(p1, p2); |
---|
3180 | \end{cfa} |
---|
3181 | |
---|
3182 | Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T. |
---|
3183 | This 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. |
---|
3184 | |
---|
3185 | |
---|
3186 | \subsection{Bounded Quantification} |
---|
3187 | |
---|
3188 | Some generic functions only work (or make sense) for any type that satisfies a given property. |
---|
3189 | For example, here is a function to pick the minimum of two values of some type. |
---|
3190 | \begin{cfa} |
---|
3191 | generic (type T | bool ?<?(T, T) ) |
---|
3192 | |
---|
3193 | T min( T a, T b ) { |
---|
3194 | return a < b ? a : b; |
---|
3195 | } |
---|
3196 | \end{cfa} |
---|
3197 | |
---|
3198 | It 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. |
---|
3199 | The ordering function used here is the less than operator, <. |
---|
3200 | The syntax used to reference the operator is discussed in further detail in Operator Overloading. |
---|
3201 | In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)). |
---|
3202 | The \CFA compiler enforces that minis only called with types for which the less than operator is defined, and reports a compile-time error otherwise. |
---|
3203 | |
---|
3204 | Bounds can also involve multiple types, and multiple requirements, as shown below: |
---|
3205 | \begin{cfa} |
---|
3206 | generic (type T, type U | { T foo(T, U); U bar(U); }) |
---|
3207 | |
---|
3208 | T baz(T t, U u) { |
---|
3209 | return foo(t, bar(u)); |
---|
3210 | } |
---|
3211 | \end{cfa} |
---|
3212 | |
---|
3213 | |
---|
3214 | \subsection{Interfaces} |
---|
3215 | |
---|
3216 | Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type. |
---|
3217 | Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined. |
---|
3218 | Can 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. |
---|
3219 | The function signature doesn't say. |
---|
3220 | |
---|
3221 | Interfaces gather together a set of function signatures under a common name, which solves two problems. |
---|
3222 | First, an interface name can be used in type bounds instead of function signatures. |
---|
3223 | This avoids repetition when a bound is used in many functions. |
---|
3224 | Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand. |
---|
3225 | \begin{cfa} |
---|
3226 | generic (type T) |
---|
3227 | interface Orderable { |
---|
3228 | bool ?<?(T, T); |
---|
3229 | }; |
---|
3230 | |
---|
3231 | generic (type T | Orderable(T)) |
---|
3232 | T min( T a, T b ) { |
---|
3233 | return a < b ? a : b; |
---|
3234 | } |
---|
3235 | \end{cfa} |
---|
3236 | |
---|
3237 | This definition of the interface Orderable makes the generic function min easier to read and understand. |
---|
3238 | Orderable can also be reused for other generic functions, max for example. |
---|
3239 | Interfaces can also build on top of other interfaces. |
---|
3240 | For example: |
---|
3241 | \begin{cfa} |
---|
3242 | generic (type T | Orderable(T) |
---|
3243 | interface FooBarable { |
---|
3244 | int foo(T, T); |
---|
3245 | int Bar(T, T); |
---|
3246 | }; |
---|
3247 | \end{cfa} |
---|
3248 | |
---|
3249 | The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition. |
---|
3250 | A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time. |
---|
3251 | For 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. |
---|
3252 | |
---|
3253 | |
---|
3254 | \subsection{Generic Typedefs} |
---|
3255 | |
---|
3256 | Type synonyms can be defined generically using the typedef keyword together with a generic type annotation. |
---|
3257 | These can be used to abbreviate complicated type expressions, especially in generic code. |
---|
3258 | \begin{cfa} |
---|
3259 | // typedef the generic function pointers for later use |
---|
3260 | |
---|
3261 | generic(type T) |
---|
3262 | typedef int (*predicate)(T); |
---|
3263 | generic(type Captured, type T) |
---|
3264 | typedef void (*callback)(Captured, T); |
---|
3265 | |
---|
3266 | generic(type T) |
---|
3267 | void find(int length, T *array, |
---|
3268 | predicate(T) p, callback(void *, T)f) { |
---|
3269 | int i; |
---|
3270 | for (i = 0; i < length; i++) |
---|
3271 | if (p(array[i])) f(NULL, array[i]); |
---|
3272 | } |
---|
3273 | \end{cfa} |
---|
3274 | |
---|
3275 | |
---|
3276 | \subsection{Generic Types} |
---|
3277 | |
---|
3278 | Generic types are defined using the same mechanisms as those described above for generic functions. |
---|
3279 | This feature allows users to create types that have one or more fields that use generic parameters as types, similar to a template classes in \Index*[C++]{\CC{}}. |
---|
3280 | For 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. |
---|
3281 | In C, something like this would have to be done using void pointers and unsafe casting. |
---|
3282 | As 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. |
---|
3283 | This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds. |
---|
3284 | |
---|
3285 | The syntax for defining a generic type looks very similar to that of a generic function. |
---|
3286 | Generic types support bounds and interfaces, using the same syntax as generic functions. |
---|
3287 | \begin{cfa} |
---|
3288 | generic (type T) |
---|
3289 | struct LinkedListElem { |
---|
3290 | T elem; |
---|
3291 | LinkedListElem(T) *next; |
---|
3292 | }; |
---|
3293 | |
---|
3294 | LinkedListElem *++?(LinkedListElem **elem) { |
---|
3295 | return *elem = elem->next; |
---|
3296 | } |
---|
3297 | |
---|
3298 | generic (type T) |
---|
3299 | struct LinkedList { |
---|
3300 | LinkedListElem(T) *head; |
---|
3301 | unsigned int size; |
---|
3302 | } |
---|
3303 | |
---|
3304 | generic (type T | bool ?==?(T, T)) |
---|
3305 | bool contains(LinkedList(T) *list, T elem) { |
---|
3306 | for(LinkedListElem *iter = list->head; iter != 0; ++iter) { |
---|
3307 | if (iter->elem == elem) return true; |
---|
3308 | } |
---|
3309 | return false; |
---|
3310 | } |
---|
3311 | \end{cfa} |
---|
3312 | |
---|
3313 | |
---|
3314 | \section{Safety} |
---|
3315 | |
---|
3316 | Safety, along with productivity, is a key goal of Do. |
---|
3317 | This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code. |
---|
3318 | |
---|
3319 | |
---|
3320 | \subsection{Exceptions} |
---|
3321 | |
---|
3322 | \CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code. |
---|
3323 | In C, developers can use error codes and special return values to report to a caller that an error occurred in a function. |
---|
3324 | The major problem with error codes is that they can be easily ignored by the caller. |
---|
3325 | Failure 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. |
---|
3326 | An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state. |
---|
3327 | |
---|
3328 | Exceptions in \CFA allow a different type of control flow. |
---|
3329 | Throwing 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. |
---|
3330 | The exception is immediately re-thrown from the parent block unless it is caught as described below. |
---|
3331 | \CFA uses keywords similar to \Index*[C++]{\CC{}} for exception handling. |
---|
3332 | An exception is thrown using a throw statement, which accepts one argument. |
---|
3333 | |
---|
3334 | \begin{cfa} |
---|
3335 | ... |
---|
3336 | |
---|
3337 | throw 13; |
---|
3338 | |
---|
3339 | ... |
---|
3340 | \end{cfa} |
---|
3341 | |
---|
3342 | An exception can be caught using a catch statement, which specifies the type of the exception it can catch. |
---|
3343 | A catch is specified immediately after a guarded block to signify that it can catch an exception from that block. |
---|
3344 | A guarded block is specified using the try keyword, followed by a block of code inside of curly braces. |
---|
3345 | |
---|
3346 | \begin{cfa} |
---|
3347 | ... |
---|
3348 | |
---|
3349 | try { |
---|
3350 | throw 13; |
---|
3351 | } |
---|
3352 | catch(int e) { |
---|
3353 | printf(.caught an exception: %d\n., e); |
---|
3354 | } |
---|
3355 | \end{cfa} |
---|
3356 | \end{comment} |
---|
3357 | |
---|
3358 | |
---|
3359 | \subsection{Memory Management} |
---|
3360 | |
---|
3361 | |
---|
3362 | \subsubsection{Manual Memory Management} |
---|
3363 | |
---|
3364 | Using malloc and free to dynamically allocate memory exposes several potential, and common, errors. |
---|
3365 | First, malloc breaks type safety because it returns a pointer to void. |
---|
3366 | There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated. |
---|
3367 | This problem is solved with a type-safe malloc. |
---|
3368 | Do.s type-safe malloc does not take any arguments for size. |
---|
3369 | Instead, it infers the type based on the return value, and then allocates space for the inferred type. |
---|
3370 | |
---|
3371 | \begin{cfa} |
---|
3372 | float *f = malloc(); // allocates the size of a float |
---|
3373 | |
---|
3374 | struct S { |
---|
3375 | int i, j, k; |
---|
3376 | }; |
---|
3377 | |
---|
3378 | struct S *s = malloc(); // allocates the size of a struct S |
---|
3379 | \end{cfa} |
---|
3380 | |
---|
3381 | In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function. |
---|
3382 | For all constructors defined for a given type (see Operator Overloading), a corresponding call to new can be used to allocate and construct that type. |
---|
3383 | |
---|
3384 | \begin{cfa} |
---|
3385 | type Complex = struct { |
---|
3386 | float real; |
---|
3387 | float imag; |
---|
3388 | }; |
---|
3389 | |
---|
3390 | // default constructor |
---|
3391 | |
---|
3392 | void ?{}(Complex &c) { |
---|
3393 | c.real = 0.0; |
---|
3394 | c.imag = 0.0; |
---|
3395 | } |
---|
3396 | |
---|
3397 | |
---|
3398 | |
---|
3399 | // 2 parameter constructor |
---|
3400 | |
---|
3401 | void ?{}(Complex &c, float real, float imag) { |
---|
3402 | c.real = real; |
---|
3403 | c.imag = imag; |
---|
3404 | } |
---|
3405 | |
---|
3406 | |
---|
3407 | int main() { |
---|
3408 | Complex c1; // No constructor is called |
---|
3409 | Complex c2{}; // Default constructor called |
---|
3410 | Complex c3{1.0, -1.0}; // 2 parameter constructor is called |
---|
3411 | |
---|
3412 | Complex *p1 = malloc(); // allocate |
---|
3413 | Complex *p2 = new(); // allocate + default constructor |
---|
3414 | Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor |
---|
3415 | } |
---|
3416 | \end{cfa} |
---|
3417 | |
---|
3418 | |
---|
3419 | \subsubsection{Automatic Memory Management} |
---|
3420 | |
---|
3421 | \CFA may also support automatic memory management to further improve safety. |
---|
3422 | If 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. |
---|
3423 | This feature requires further investigation. |
---|
3424 | \CFA will not have a garbage collector, but might use some kind of region-based memory management. |
---|
3425 | |
---|
3426 | |
---|
3427 | \begin{comment} |
---|
3428 | \subsection{Unsafe C Constructs} |
---|
3429 | |
---|
3430 | C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming. |
---|
3431 | Some of these practices however are often error-prone and difficult to read and maintain. |
---|
3432 | Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code. |
---|
3433 | If 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. |
---|
3434 | This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway.. |
---|
3435 | |
---|
3436 | The 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. |
---|
3437 | Once the full set is decided, the rules will be listed here. |
---|
3438 | \end{comment} |
---|
3439 | |
---|
3440 | |
---|
3441 | \section{Concurrency} |
---|
3442 | |
---|
3443 | Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads. |
---|
3444 | The model integrates concurrency features into the language by making the structure type the core unit of concurrency. |
---|
3445 | All communication occurs through method calls, where data is sent via method arguments, and received via the return value. |
---|
3446 | This enables a very familiar interface to all programmers, even those with no parallel programming experience. |
---|
3447 | It also allows the compiler to do static type checking of all communication, a very important safety feature. |
---|
3448 | This controlled communication with type safety has some similarities with channels in \Index*{Go}, and can actually implement channels exactly, as well as create additional communication patterns that channels cannot. |
---|
3449 | Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads. |
---|
3450 | |
---|
3451 | \begin{figure} |
---|
3452 | \begin{cfa} |
---|
3453 | #include <fstream> |
---|
3454 | #include <coroutine> |
---|
3455 | |
---|
3456 | coroutine Fibonacci { |
---|
3457 | int fn; §\C{// used for communication}§ |
---|
3458 | }; |
---|
3459 | void ?{}( Fibonacci * this ) { |
---|
3460 | this->fn = 0; |
---|
3461 | } |
---|
3462 | void main( Fibonacci * this ) { |
---|
3463 | int fn1, fn2; §\C{// retained between resumes}§ |
---|
3464 | this->fn = 0; §\C{// case 0}§ |
---|
3465 | fn1 = this->fn; |
---|
3466 | suspend(); §\C{// return to last resume}§ |
---|
3467 | |
---|
3468 | this->fn = 1; §\C{// case 1}§ |
---|
3469 | fn2 = fn1; |
---|
3470 | fn1 = this->fn; |
---|
3471 | suspend(); §\C{// return to last resume}§ |
---|
3472 | |
---|
3473 | for ( ;; ) { §\C{// general case}§ |
---|
3474 | this->fn = fn1 + fn2; |
---|
3475 | fn2 = fn1; |
---|
3476 | fn1 = this->fn; |
---|
3477 | suspend(); §\C{// return to last resume}§ |
---|
3478 | } // for |
---|
3479 | } |
---|
3480 | int next( Fibonacci * this ) { |
---|
3481 | resume( this ); §\C{// transfer to last suspend}§ |
---|
3482 | return this->fn; |
---|
3483 | } |
---|
3484 | int main() { |
---|
3485 | Fibonacci f1, f2; |
---|
3486 | for ( int i = 1; i <= 10; i += 1 ) { |
---|
3487 | sout | next( &f1 ) | ' ' | next( &f2 ) | endl; |
---|
3488 | } // for |
---|
3489 | } |
---|
3490 | \end{cfa} |
---|
3491 | \caption{Fibonacci Coroutine} |
---|
3492 | \label{f:FibonacciCoroutine} |
---|
3493 | \end{figure} |
---|
3494 | |
---|
3495 | |
---|
3496 | \subsection{Coroutine} |
---|
3497 | |
---|
3498 | \Index{Coroutines} are the precursor to tasks. |
---|
3499 | \VRef[Figure]{f:FibonacciCoroutine} shows a coroutine that computes the \Index*{Fibonacci} numbers. |
---|
3500 | |
---|
3501 | |
---|
3502 | \subsection{Monitors} |
---|
3503 | |
---|
3504 | A monitor is a structure in \CFA which includes implicit locking of its fields. |
---|
3505 | Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion. |
---|
3506 | An example of the definition of a monitor is shown here: |
---|
3507 | \begin{cfa} |
---|
3508 | type Account = monitor { |
---|
3509 | const unsigned long number; // account number |
---|
3510 | float balance; // account balance |
---|
3511 | }; |
---|
3512 | \end{cfa} |
---|
3513 | |
---|
3514 | \begin{figure} |
---|
3515 | \begin{cfa} |
---|
3516 | #include <fstream> |
---|
3517 | #include <kernel> |
---|
3518 | #include <monitor> |
---|
3519 | #include <thread> |
---|
3520 | |
---|
3521 | monitor global_t { |
---|
3522 | int value; |
---|
3523 | }; |
---|
3524 | |
---|
3525 | void ?{}(global_t * this) { |
---|
3526 | this->value = 0; |
---|
3527 | } |
---|
3528 | |
---|
3529 | static global_t global; |
---|
3530 | |
---|
3531 | void increment3( global_t * mutex this ) { |
---|
3532 | this->value += 1; |
---|
3533 | } |
---|
3534 | void increment2( global_t * mutex this ) { |
---|
3535 | increment3( this ); |
---|
3536 | } |
---|
3537 | void increment( global_t * mutex this ) { |
---|
3538 | increment2( this ); |
---|
3539 | } |
---|
3540 | |
---|
3541 | thread MyThread {}; |
---|
3542 | |
---|
3543 | void main( MyThread* this ) { |
---|
3544 | for(int i = 0; i < 1_000_000; i++) { |
---|
3545 | increment( &global ); |
---|
3546 | } |
---|
3547 | } |
---|
3548 | int main(int argc, char* argv[]) { |
---|
3549 | processor p; |
---|
3550 | { |
---|
3551 | MyThread f[4]; |
---|
3552 | } |
---|
3553 | sout | global.value | endl; |
---|
3554 | } |
---|
3555 | \end{cfa} |
---|
3556 | \caption{Atomic-Counter Monitor} |
---|
3557 | \caption{f:AtomicCounterMonitor} |
---|
3558 | \end{figure} |
---|
3559 | |
---|
3560 | \begin{comment} |
---|
3561 | Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor; |
---|
3562 | it is always passed by reference. |
---|
3563 | Users can specify to the compiler whether or not a function will require mutual exclusion of the monitor using the mutex modifier on the parameter. |
---|
3564 | When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body. |
---|
3565 | This means that a function requiring mutual exclusion could block if the lock is already held by another thread. |
---|
3566 | Blocking 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. |
---|
3567 | If multiple mutex parameters are specified, they will be locked in parameter order (\ie first parameter is locked first) and unlocked in the |
---|
3568 | reverse order. |
---|
3569 | \begin{cfa} |
---|
3570 | // This function accesses a constant field, it does not require |
---|
3571 | // mutual exclusion |
---|
3572 | |
---|
3573 | export unsigned long getAccountNumber(Account &a) { |
---|
3574 | return a.number; |
---|
3575 | } |
---|
3576 | |
---|
3577 | // This function accesses and modifies a shared field; it |
---|
3578 | // requires mutual exclusion |
---|
3579 | |
---|
3580 | export float withdrawal(mutex Account &a, float amount) { |
---|
3581 | a.balance -= amount; |
---|
3582 | return a.balance; |
---|
3583 | } |
---|
3584 | \end{cfa} |
---|
3585 | |
---|
3586 | Often, one function using a monitor will call another function using that same monitor. |
---|
3587 | If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function. |
---|
3588 | This 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. |
---|
3589 | It will still be unlocked the same number of times. |
---|
3590 | An example of this situation is shown below: |
---|
3591 | |
---|
3592 | \begin{cfa} |
---|
3593 | // deleting a job from a worker requires mutual exclusion |
---|
3594 | |
---|
3595 | void deleteJob(mutex Worker &w, Job &j) { |
---|
3596 | ... |
---|
3597 | } |
---|
3598 | |
---|
3599 | // transferring requires mutual exclusion and calls deleteJob |
---|
3600 | |
---|
3601 | void transferJob(mutex Worker &from, Worker &to) { |
---|
3602 | ... |
---|
3603 | deleteJob(j); |
---|
3604 | ... |
---|
3605 | } |
---|
3606 | \end{cfa} |
---|
3607 | \end{comment} |
---|
3608 | |
---|
3609 | |
---|
3610 | \subsection{Tasks} |
---|
3611 | |
---|
3612 | \CFA also provides a simple mechanism for creating and utilizing user level threads. |
---|
3613 | A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control. |
---|
3614 | Similar to a monitor, a task is defined like a structure: |
---|
3615 | |
---|
3616 | \begin{figure} |
---|
3617 | \begin{cfa} |
---|
3618 | #include <fstream> |
---|
3619 | #include <kernel> |
---|
3620 | #include <stdlib> |
---|
3621 | #include <thread> |
---|
3622 | |
---|
3623 | thread First { signal_once * lock; }; |
---|
3624 | thread Second { signal_once * lock; }; |
---|
3625 | |
---|
3626 | void ?{}( First * this, signal_once* lock ) { this->lock = lock; } |
---|
3627 | void ?{}( Second * this, signal_once* lock ) { this->lock = lock; } |
---|
3628 | |
---|
3629 | void main( First * this ) { |
---|
3630 | for ( int i = 0; i < 10; i += 1 ) { |
---|
3631 | sout | "First : Suspend No." | i + 1 | endl; |
---|
3632 | yield(); |
---|
3633 | } |
---|
3634 | signal( this->lock ); |
---|
3635 | } |
---|
3636 | |
---|
3637 | void main( Second * this ) { |
---|
3638 | wait( this->lock ); |
---|
3639 | for ( int i = 0; i < 10; i += 1 ) { |
---|
3640 | sout | "Second : Suspend No." | i + 1 | endl; |
---|
3641 | yield(); |
---|
3642 | } |
---|
3643 | } |
---|
3644 | |
---|
3645 | int main( void ) { |
---|
3646 | signal_once lock; |
---|
3647 | sout | "User main begin" | endl; |
---|
3648 | { |
---|
3649 | processor p; |
---|
3650 | { |
---|
3651 | First f = { &lock }; |
---|
3652 | Second s = { &lock }; |
---|
3653 | } |
---|
3654 | } |
---|
3655 | sout | "User main end" | endl; |
---|
3656 | } |
---|
3657 | \end{cfa} |
---|
3658 | \caption{Simple Tasks} |
---|
3659 | \label{f:SimpleTasks} |
---|
3660 | \end{figure} |
---|
3661 | |
---|
3662 | |
---|
3663 | \begin{comment} |
---|
3664 | \begin{cfa} |
---|
3665 | type Adder = task { |
---|
3666 | int *row; |
---|
3667 | int size; |
---|
3668 | int &subtotal; |
---|
3669 | } |
---|
3670 | \end{cfa} |
---|
3671 | |
---|
3672 | A task may define a constructor, which will be called upon allocation and run on the caller.s thread. |
---|
3673 | A destructor may also be defined, which is called at deallocation (when a dynamic object is deleted or when a local object goes out of scope). |
---|
3674 | After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method. |
---|
3675 | All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error. |
---|
3676 | Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads. |
---|
3677 | (Note that this example is designed to display the syntax and functionality, not the best method to solve this problem) |
---|
3678 | \begin{cfa} |
---|
3679 | void ?{}(Adder &a, int r[], int s, int &st) { // constructor |
---|
3680 | a.row = r; |
---|
3681 | a.size = s; |
---|
3682 | a.subtotal = st; |
---|
3683 | } |
---|
3684 | |
---|
3685 | // implicitly spawn thread and begin execution here |
---|
3686 | |
---|
3687 | void ?()(Adder &a) { |
---|
3688 | int c; |
---|
3689 | subtotal = 0; |
---|
3690 | for (c=0; c<a.size; ++c) { |
---|
3691 | subtotal += row[c]; |
---|
3692 | } |
---|
3693 | } |
---|
3694 | |
---|
3695 | int main() { |
---|
3696 | const int rows = 100, cols = 1000000; |
---|
3697 | int matrix[rows][cols]; |
---|
3698 | int subtotals[rows]; |
---|
3699 | int total = 0; |
---|
3700 | int r; |
---|
3701 | |
---|
3702 | { // create a new scope here for our adders |
---|
3703 | Adder adders[rows]; |
---|
3704 | // read in the matrix |
---|
3705 | ... |
---|
3706 | for (r=0; r<rows; ++r) { |
---|
3707 | // tasks are initialized on this thread |
---|
3708 | Adders[r] = {matrix[r], cols, subtotals[r]}; |
---|
3709 | Adders[r](); // spawn thread and begin execution |
---|
3710 | } |
---|
3711 | } // adders go out of scope; block here until they all finish |
---|
3712 | total += subtotals[r]; |
---|
3713 | printf(.total is %d\n., total); |
---|
3714 | } |
---|
3715 | \end{cfa} |
---|
3716 | |
---|
3717 | \subsection{Cooperative Scheduling} |
---|
3718 | |
---|
3719 | Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points. |
---|
3720 | In Listing 31, there are no yield points, so each task runs to completion with no interruptions. |
---|
3721 | Places 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. |
---|
3722 | This 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. |
---|
3723 | For example, the code below defines a monitor that maintains a generic list. |
---|
3724 | When 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. |
---|
3725 | Similarly, 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. |
---|
3726 | |
---|
3727 | \begin{cfa} |
---|
3728 | // type T is used as a generic type for all definitions inside |
---|
3729 | // the curly brackets |
---|
3730 | |
---|
3731 | generic(type T) { |
---|
3732 | type Channel = monitor { |
---|
3733 | List(T) list; // list is a simple generic list type |
---|
3734 | }; |
---|
3735 | |
---|
3736 | T pop(mutex &Channel(T) ch) { |
---|
3737 | if (ch.list.empty()) { |
---|
3738 | // yield until push is called for this channel |
---|
3739 | yield(push); |
---|
3740 | } |
---|
3741 | return ch.list.pop(); |
---|
3742 | } |
---|
3743 | |
---|
3744 | void push(mutex &Channel(T)ch, T val) { |
---|
3745 | if (ch.list.full()) { |
---|
3746 | // yield until pop is called for this channel |
---|
3747 | yield(pop); |
---|
3748 | } |
---|
3749 | ch.list.push(val); |
---|
3750 | } |
---|
3751 | } |
---|
3752 | \end{cfa} |
---|
3753 | |
---|
3754 | A task can also yield indefinitely by calling yield with no arguments. |
---|
3755 | This will tell the scheduler to yield this task until it is resumed by some other task. |
---|
3756 | A task can resume another task by using its functional call operator. |
---|
3757 | The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods. |
---|
3758 | |
---|
3759 | \begin{cfa} |
---|
3760 | type Ping = task { |
---|
3761 | Pong *partner; |
---|
3762 | }; |
---|
3763 | |
---|
3764 | void ?{}(Ping &p, Pong *partner = 0) { |
---|
3765 | p.partner = partner; |
---|
3766 | } |
---|
3767 | |
---|
3768 | void ?()(Ping &p) { |
---|
3769 | for(;;) { // loop forever |
---|
3770 | printf(.ping\n.); |
---|
3771 | partner(); // resumes the partner task |
---|
3772 | yield(); // yields this task |
---|
3773 | } |
---|
3774 | } |
---|
3775 | |
---|
3776 | type Pong = task { |
---|
3777 | Ping *partner; |
---|
3778 | }; |
---|
3779 | |
---|
3780 | void ?{}(Pong &p, Ping *partner = 0) { |
---|
3781 | p.partner = partner; |
---|
3782 | } |
---|
3783 | |
---|
3784 | void ?()(Pong &p) { |
---|
3785 | for(;;) { // loop forever |
---|
3786 | yield(); // yields this task |
---|
3787 | printf(.pong/n.); |
---|
3788 | partner(); // resumes the partner task |
---|
3789 | } |
---|
3790 | } |
---|
3791 | |
---|
3792 | void main() { |
---|
3793 | Ping ping; // allocate ping |
---|
3794 | Pong pong{ping}; // allocate, initialize, and start pong |
---|
3795 | Ping{pong}; // initialize and start ping |
---|
3796 | } |
---|
3797 | \end{cfa} |
---|
3798 | |
---|
3799 | The same functionality can be accomplished by providing functions to be called by the partner task. |
---|
3800 | \begin{cfa} |
---|
3801 | type Pingpong = task { |
---|
3802 | String msg; |
---|
3803 | Pingpong *partner; |
---|
3804 | }; |
---|
3805 | |
---|
3806 | void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) { |
---|
3807 | p.msg = msg; |
---|
3808 | p.partner = partner; |
---|
3809 | } |
---|
3810 | |
---|
3811 | void ?()(Pingpong &p) { |
---|
3812 | for(;;) { |
---|
3813 | yield(go); |
---|
3814 | } |
---|
3815 | } |
---|
3816 | |
---|
3817 | void go(Pingpong &p) { |
---|
3818 | print(.%(p.msg)\n.); |
---|
3819 | go(p.partner); |
---|
3820 | } |
---|
3821 | |
---|
3822 | void main() { |
---|
3823 | Pingpong ping = {.ping.}; |
---|
3824 | Pingpong pong = {.pong., ping}; |
---|
3825 | ping.partner = pong; |
---|
3826 | go(ping); |
---|
3827 | } |
---|
3828 | \end{cfa} |
---|
3829 | \end{comment} |
---|
3830 | |
---|
3831 | |
---|
3832 | \begin{comment} |
---|
3833 | \section{Modules and Packages } |
---|
3834 | |
---|
3835 | High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed. |
---|
3836 | \CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time. |
---|
3837 | |
---|
3838 | There are two levels of encapsulation in \CFA, module and package. |
---|
3839 | A module is a logical grouping of functionality that can be easily pulled into another project, much like a module in \Index*{Python} or a package in \Index*{Go}. |
---|
3840 | A module forms a namespace to limit the visibility and prevent naming conflicts of variables. |
---|
3841 | Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed. |
---|
3842 | |
---|
3843 | A package is a physical grouping of one or more modules that is used for code distribution and version management. |
---|
3844 | Package is also the level of granularity at which dependences are managed. |
---|
3845 | A package is similar to the Crate in \Index*{Rust}. |
---|
3846 | |
---|
3847 | |
---|
3848 | \subsection{No Declarations, No Header Files} |
---|
3849 | |
---|
3850 | In C and \Index*[C++]{\CC{}}, it is necessary to declare or define every global variable, global function, and type before it is used in each file. |
---|
3851 | Header files and a preprocessor are normally used to avoid repeating code. |
---|
3852 | Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work. |
---|
3853 | Instead of following this model, the \CFA tools can extract all of the same information from the code automatically. |
---|
3854 | This 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. |
---|
3855 | In 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. |
---|
3856 | This seems like a minor change, but according to (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering), this simple change can cause massive reductions in compile time. |
---|
3857 | |
---|
3858 | In \CFA, multiple definitions are not necessary. |
---|
3859 | Within a module, all of the module's global definitions are visible throughout the module. |
---|
3860 | For example, the following code compiles, even though ©isOdd© was not declared before being called: |
---|
3861 | \begin{cfa} |
---|
3862 | bool isEven(unsigned int x) { |
---|
3863 | if (x == 0) return true; |
---|
3864 | else return !isOdd(x); |
---|
3865 | } |
---|
3866 | |
---|
3867 | bool isOdd(unsigned int x) { |
---|
3868 | if (x == 1) return true; |
---|
3869 | else return !isEven(x - 2); |
---|
3870 | } |
---|
3871 | \end{cfa} |
---|
3872 | |
---|
3873 | Header files in C are used to expose the declarations from a library, so that they can be used externally. |
---|
3874 | With \CFA, this functionality is replaced with module exports, discussed below. |
---|
3875 | When 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. |
---|
3876 | |
---|
3877 | In 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). |
---|
3878 | |
---|
3879 | |
---|
3880 | \subsection{Modules} |
---|
3881 | |
---|
3882 | A 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. |
---|
3883 | These modules can then be easily shared and reused in multiple projects. |
---|
3884 | As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces. |
---|
3885 | |
---|
3886 | \CFA adds the following keywords to express the module systems: module, export, import, as. |
---|
3887 | |
---|
3888 | |
---|
3889 | \subsubsection{Module Declaration} |
---|
3890 | |
---|
3891 | The syntax to declare a module is module moduleName;. |
---|
3892 | |
---|
3893 | The module declaration must be at the beginning of a file, and each file can only belong to one module. |
---|
3894 | If there is no module declaration at the beginning of a file, the file belongs to the global module. |
---|
3895 | A module can span several files. |
---|
3896 | By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation. |
---|
3897 | |
---|
3898 | The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship. |
---|
3899 | For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container. |
---|
3900 | |
---|
3901 | Only the interfaces of a module are visible from outside, when the module is imported. export is a type decorator to declare a module interface. |
---|
3902 | A method, a global variable or a type can be declared as a module interface. |
---|
3903 | Types defined in a module and referenced by an exported function or a variable must be exported, too. |
---|
3904 | |
---|
3905 | The following code is a simple module declaration example. |
---|
3906 | \begin{cfa} |
---|
3907 | module M; |
---|
3908 | |
---|
3909 | //visible outside module M |
---|
3910 | |
---|
3911 | export int f(int i) { return i + 1; } |
---|
3912 | export double aCounter; |
---|
3913 | |
---|
3914 | //not visible outside module M |
---|
3915 | |
---|
3916 | int g(int i) { return i - 1; } |
---|
3917 | |
---|
3918 | double bCounter; |
---|
3919 | \end{cfa} |
---|
3920 | |
---|
3921 | export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module. |
---|
3922 | |
---|
3923 | |
---|
3924 | \subsubsection{Module Import} |
---|
3925 | |
---|
3926 | The syntax to import a module is import moduleName; or import moduleName as anotherName;. |
---|
3927 | One package cannot be imported with both of the two types of syntax in one file. |
---|
3928 | A package imported in one file will only be visible in this file. |
---|
3929 | For example, two files, A and B belong to the same module. |
---|
3930 | If file A imports another module, M, the exported names in M are not visible in file B. |
---|
3931 | |
---|
3932 | All of the exported names are visible in the file that imports the module. |
---|
3933 | The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo). |
---|
3934 | If 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(...);). |
---|
3935 | The 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. |
---|
3936 | Conflicts in namespaces will be reported by the compiler. |
---|
3937 | The second method can be used to solve conflicting name problems. |
---|
3938 | The following code snippets show the two situations. |
---|
3939 | |
---|
3940 | \begin{cfa} |
---|
3941 | module util/counter; |
---|
3942 | export int f(int i) { return i+1; } |
---|
3943 | |
---|
3944 | import util/counter; |
---|
3945 | |
---|
3946 | int main() { |
---|
3947 | return counter.f(200); // f() from the package counter |
---|
3948 | } |
---|
3949 | |
---|
3950 | import util/counter as ct; |
---|
3951 | int main() { |
---|
3952 | return ct.f(200); // f() from the package counter |
---|
3953 | } |
---|
3954 | \end{cfa} |
---|
3955 | |
---|
3956 | |
---|
3957 | Additionally, 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. |
---|
3958 | |
---|
3959 | \begin{cfa} |
---|
3960 | module M1; |
---|
3961 | export int f(int i) { return i+1;} // visible outside |
---|
3962 | |
---|
3963 | int g(int i) { return i-1;} // not visible outside |
---|
3964 | |
---|
3965 | module M2; |
---|
3966 | int f(int i) { return i * 2; } // not visible outside |
---|
3967 | export int g(int g) { return i / 2; } // visible outside |
---|
3968 | |
---|
3969 | import M1 as .; |
---|
3970 | |
---|
3971 | import M2 as .; |
---|
3972 | |
---|
3973 | |
---|
3974 | int main() { |
---|
3975 | return f(3) + g(4); //f() from M1 and g() from M2; |
---|
3976 | } |
---|
3977 | \end{cfa} |
---|
3978 | |
---|
3979 | |
---|
3980 | \subsubsection{Sub-Module and Module Aggregation} |
---|
3981 | |
---|
3982 | Several modules can be organized in a parent module and sub-modules relationship. |
---|
3983 | The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship. |
---|
3984 | For example, std/vector and std/io are sub-modules of module std. |
---|
3985 | The 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 |
---|
3986 | not implicitly exported in the parent module. |
---|
3987 | |
---|
3988 | Aggregation is a mechanism to support components and simplified importing. |
---|
3989 | The mechanism is not based on naming but based on manual declaration. |
---|
3990 | For example, the following is the aggregated sequence module. |
---|
3991 | The export {...} is syntactic sugar for many lines of export module aModule;. |
---|
3992 | If an aggregated module is imported, all the included modules in the aggregation are imported. |
---|
3993 | |
---|
3994 | \begin{cfa} |
---|
3995 | module std/sequence; |
---|
3996 | |
---|
3997 | export { |
---|
3998 | module std/vector; |
---|
3999 | module std/list; |
---|
4000 | module std/array; |
---|
4001 | module std/deque; |
---|
4002 | module std/forward_list; |
---|
4003 | module std/queue; |
---|
4004 | module std/stack; |
---|
4005 | }; |
---|
4006 | \end{cfa} |
---|
4007 | |
---|
4008 | After importing the aggregated module, each individual name is still contained in the original name space. |
---|
4009 | For 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. |
---|
4010 | |
---|
4011 | |
---|
4012 | \subsubsection{Import from Repository} |
---|
4013 | |
---|
4014 | When 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). |
---|
4015 | The tools also support retrieving modules of a package from external repositories. |
---|
4016 | See Listing 40: Package directory structure |
---|
4017 | |
---|
4018 | |
---|
4019 | \subsubsection{Package Import} |
---|
4020 | |
---|
4021 | Because 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. |
---|
4022 | In 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; |
---|
4023 | or 2) Adding the package dependence into the current project's Do.prj. |
---|
4024 | More details about locating a module in a package are explained in the next section. |
---|
4025 | |
---|
4026 | |
---|
4027 | \subsubsection{Package Versioning} |
---|
4028 | |
---|
4029 | A package must have a version number. |
---|
4030 | The version number is a string. |
---|
4031 | For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers. |
---|
4032 | By convention, a package is stored in a directory named packageName-packageVersion. |
---|
4033 | For example, the util package with version 1.1 is stored in a directory named util-1.1. |
---|
4034 | |
---|
4035 | The project description file can optionally specify the version of the package used in the current project. |
---|
4036 | If 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. |
---|
4037 | The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds. |
---|
4038 | |
---|
4039 | |
---|
4040 | \subsection{Module and Package Organization} |
---|
4041 | |
---|
4042 | \CFA has two level of encapsulations, module and package. |
---|
4043 | This section explains the object model of modules, packages and other language concepts. |
---|
4044 | It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation. |
---|
4045 | |
---|
4046 | |
---|
4047 | \subsubsection{Object Model} |
---|
4048 | |
---|
4049 | There are several concepts in Do. |
---|
4050 | \begin{itemize} |
---|
4051 | \item |
---|
4052 | File: a \CFA source file |
---|
4053 | \item |
---|
4054 | Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside |
---|
4055 | \item |
---|
4056 | Package: a container to organize modules for distribution; It has attributes like name, author, |
---|
4057 | version, dependences, etc. |
---|
4058 | \item |
---|
4059 | Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc. |
---|
4060 | \end{itemize} |
---|
4061 | |
---|
4062 | The following rules summarize the object model of all the above concepts: |
---|
4063 | \begin{itemize} |
---|
4064 | \item |
---|
4065 | A module contains one or more files |
---|
4066 | \begin{itemize} |
---|
4067 | \item |
---|
4068 | One file can only belong to one module |
---|
4069 | \item |
---|
4070 | A module has its name and interfaces exported |
---|
4071 | \item |
---|
4072 | A file without a module declaration at the beginning belongs to the global module |
---|
4073 | \item |
---|
4074 | \end{itemize} |
---|
4075 | |
---|
4076 | \item |
---|
4077 | A package contains one or more modules |
---|
4078 | \begin{itemize} |
---|
4079 | \item |
---|
4080 | A package has additional meta info described in Do.prj file |
---|
4081 | \item |
---|
4082 | A package may be dependent on other packages. |
---|
4083 | \end{itemize} |
---|
4084 | |
---|
4085 | \item |
---|
4086 | A project contains one or more modules in its source code |
---|
4087 | \begin{itemize} |
---|
4088 | \item |
---|
4089 | A project has additional meta info described in Do.prj file |
---|
4090 | \item |
---|
4091 | A project may be dependent on other packages |
---|
4092 | \item |
---|
4093 | A project can be transformed into a package for distribution |
---|
4094 | \item |
---|
4095 | A project can generate one or more executable binaries |
---|
4096 | \end{itemize} |
---|
4097 | \end{itemize} |
---|
4098 | |
---|
4099 | |
---|
4100 | \subsubsection{Module File Organization} |
---|
4101 | |
---|
4102 | The rules of this section are the conventions to organize module files in one package. |
---|
4103 | |
---|
4104 | The file location of a module in a package must match the module/submodule naming hierarchy. |
---|
4105 | The names separated by slash "/" must match the directory levels. |
---|
4106 | If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory. |
---|
4107 | The file can be put inside its parent module's sub-directory with the sub module's name as the file name. |
---|
4108 | |
---|
4109 | Here is an example of a package, util. |
---|
4110 | \begin{cfa} |
---|
4111 | + util |
---|
4112 | Do.prj #package description file |
---|
4113 | heap.do #Case 1: module heap; |
---|
4114 | list.do #Case 1: mdoule list; |
---|
4115 | ring.do #Case 1: module ring; |
---|
4116 | + string #Case 2 |
---|
4117 | impl1.do #module string; |
---|
4118 | + std |
---|
4119 | vector.do |
---|
4120 | list.do |
---|
4121 | + array #Case 3 |
---|
4122 | array1.do #module std/array; |
---|
4123 | array2.do #module std/array; |
---|
4124 | sequence.do #Case 4, module std/sequence; |
---|
4125 | test.do #Case 5 |
---|
4126 | \end{cfa} |
---|
4127 | |
---|
4128 | \begin{itemize} |
---|
4129 | \item |
---|
4130 | Case 1: Each individual file implements a module |
---|
4131 | \item |
---|
4132 | Case 2: Put the implementation of a module under the sub-directory, but there is only one file |
---|
4133 | \item |
---|
4134 | Case 3: Put the implementation of a module under the sub-directory; There are several files to |
---|
4135 | implement one module |
---|
4136 | \item |
---|
4137 | Case 4: One file to express one aggregation |
---|
4138 | \item |
---|
4139 | Case 5: The file does not belong to any module; It is used for testing purpose |
---|
4140 | \end{itemize} |
---|
4141 | |
---|
4142 | The example only uses source code, ".do" files, to show the module file organization. |
---|
4143 | Other module packaging formats, like binary, must also follow the same rules. |
---|
4144 | |
---|
4145 | |
---|
4146 | \subsection{Module File Format} |
---|
4147 | |
---|
4148 | \CFA supports different types of module file formats. |
---|
4149 | |
---|
4150 | \begin{itemize} |
---|
4151 | \item |
---|
4152 | Pure source code format: The files should be organized following the previous section's definition. |
---|
4153 | \item |
---|
4154 | IR format (TBD): The \CFA compiler IR format, similar to the source code format |
---|
4155 | \item |
---|
4156 | Binary format, including ".a" static library or ".so" dynamic linkage library |
---|
4157 | \begin{itemize} |
---|
4158 | \item |
---|
4159 | The file's name must match the right level's module name defined in the previous section |
---|
4160 | \item |
---|
4161 | E.g. "util.so" includes all modules for the package util. |
---|
4162 | \item |
---|
4163 | E.g. "string.so" under the package directory to include files belonging to "module string;" |
---|
4164 | \end{itemize} |
---|
4165 | \item. |
---|
4166 | Archive format |
---|
4167 | \begin{itemize} |
---|
4168 | \item |
---|
4169 | The archive is named as ".dar", and is a zip archive of the source code or the binary for a package |
---|
4170 | \item |
---|
4171 | E.g. "util.dar" is the whole package for util package including the package direction file |
---|
4172 | \end{itemize} |
---|
4173 | \item |
---|
4174 | Hybrid format |
---|
4175 | \begin{itemize} |
---|
4176 | \item |
---|
4177 | A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format |
---|
4178 | \item |
---|
4179 | The only limitation is that the names of the files must match the module location names defined in previous section |
---|
4180 | \end{itemize} |
---|
4181 | \end{itemize} |
---|
4182 | Package and Module Locating and the \CFA Language Tooling documentation for more details. |
---|
4183 | |
---|
4184 | |
---|
4185 | \subsection{Packages} |
---|
4186 | |
---|
4187 | A package is synonymous with a library in other languages. |
---|
4188 | The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management. |
---|
4189 | A package is a physical grouping of one or more modules in a directory (an archive file for a directory). |
---|
4190 | The 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. |
---|
4191 | |
---|
4192 | |
---|
4193 | \subsubsection{Package Definition} |
---|
4194 | |
---|
4195 | A package is defined by putting a project description file, Do.prj, with one or more modules into a directory. |
---|
4196 | This project description file contains the package's meta data, including package name, author, version, dependences, etc. |
---|
4197 | It should be in the root of the package directory. |
---|
4198 | |
---|
4199 | The modules in the package could be either source code, or compiled binary format. |
---|
4200 | The location of the module files should follow the module name's path. |
---|
4201 | |
---|
4202 | Here is a simple example of the directory structure of a package, core. |
---|
4203 | It contains a module std and several sub-modules under std. |
---|
4204 | \begin{cfa} |
---|
4205 | + core |
---|
4206 | Do.prj |
---|
4207 | + std |
---|
4208 | + io |
---|
4209 | file.do # module std/io/file; |
---|
4210 | network.do #module std/io/network; |
---|
4211 | + container |
---|
4212 | vector.do #module std/container/vector; |
---|
4213 | list.do #module std/container/list; |
---|
4214 | \end{cfa} |
---|
4215 | |
---|
4216 | |
---|
4217 | \subsubsection{Package Import} |
---|
4218 | |
---|
4219 | Because 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. |
---|
4220 | In 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. |
---|
4221 | More details about locating a module in a package are explained in the next section. |
---|
4222 | |
---|
4223 | |
---|
4224 | \subsubsection{Package Versioning} |
---|
4225 | |
---|
4226 | A package must have a version number. |
---|
4227 | The version number is a string. |
---|
4228 | For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers. |
---|
4229 | By convention, a package is stored in a directory named packageName-packageVersion. |
---|
4230 | For example, the util package with version 1.1 is stored in a directory named util-1.1. |
---|
4231 | |
---|
4232 | The project description file can optionally specify the version of the package used in the current project. |
---|
4233 | If 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. |
---|
4234 | The builder tool will record the specific package version used in the build in the project's "Do.lock" file to enable fully repeatable builds. |
---|
4235 | |
---|
4236 | |
---|
4237 | \subsection{Module and Package Organization} |
---|
4238 | |
---|
4239 | \CFA has two level of encapsulations, module and package. |
---|
4240 | This section explains the object model of modules, packages and other language concepts. |
---|
4241 | It also explains how programmers should organize their code, and the method used by the build tools to locate packages, and import modules for compilation. |
---|
4242 | |
---|
4243 | |
---|
4244 | \subsubsection{Object Model} |
---|
4245 | |
---|
4246 | There are several concepts in Do. |
---|
4247 | \begin{itemize} |
---|
4248 | \item |
---|
4249 | File: a \CFA source file |
---|
4250 | \item |
---|
4251 | Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside |
---|
4252 | \item |
---|
4253 | Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc. |
---|
4254 | \item |
---|
4255 | Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc. |
---|
4256 | \end{itemize} |
---|
4257 | |
---|
4258 | The following rules summarize the object model of all the above concepts: |
---|
4259 | \begin{itemize} |
---|
4260 | \item |
---|
4261 | A module contains one or more files |
---|
4262 | \begin{itemize} |
---|
4263 | \item |
---|
4264 | One file can only belong to one module |
---|
4265 | \item |
---|
4266 | A module has its name and interfaces exported |
---|
4267 | \item |
---|
4268 | A file without a module declaration at the beginning belongs to the global module |
---|
4269 | \end{itemize} |
---|
4270 | \item |
---|
4271 | A package contains one or more modules |
---|
4272 | \begin{itemize} |
---|
4273 | \item |
---|
4274 | A package has additional meta info described in Do.prj file |
---|
4275 | \item |
---|
4276 | A package may be dependent on other packages. |
---|
4277 | \end{itemize} |
---|
4278 | \item |
---|
4279 | A project contains one or more modules in its source code |
---|
4280 | \begin{itemize} |
---|
4281 | \item |
---|
4282 | A project has additional meta info described in Do.prj file |
---|
4283 | \item |
---|
4284 | A project may be dependent on other packages |
---|
4285 | \item |
---|
4286 | A project can be transformed into a package for distribution |
---|
4287 | \item |
---|
4288 | A project can generate one or more executable binaries |
---|
4289 | \end{itemize} |
---|
4290 | \end{itemize} |
---|
4291 | |
---|
4292 | |
---|
4293 | \subsubsection{Module File Organization} |
---|
4294 | |
---|
4295 | The rules of this section are the conventions to organize module files in one package. |
---|
4296 | |
---|
4297 | The file location of a module in a package must match the module/submodule naming hierarchy. |
---|
4298 | The names separated by slash "/" must match the directory levels. |
---|
4299 | If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory. |
---|
4300 | The file can be put inside its parent module's sub-directory with the sub module's name as the file name. |
---|
4301 | |
---|
4302 | Here is an example of a package, util. |
---|
4303 | \begin{cfa} |
---|
4304 | + util |
---|
4305 | Do.prj #package description file |
---|
4306 | heap.do #Case 1: module heap; |
---|
4307 | list.do #Case 1: mdoule list; |
---|
4308 | ring.do #Case 1: module ring; |
---|
4309 | + string #Case 2 |
---|
4310 | impl1.do #module string; |
---|
4311 | + std |
---|
4312 | vector.do |
---|
4313 | list.do |
---|
4314 | + array #Case 3 |
---|
4315 | array1.do #module std/array; |
---|
4316 | array2.do #module std/array; |
---|
4317 | sequence.do #Case 4, module std/sequence; |
---|
4318 | test.do #Case 5 |
---|
4319 | \end{cfa} |
---|
4320 | |
---|
4321 | |
---|
4322 | \begin{itemize} |
---|
4323 | \item |
---|
4324 | Case 1: Each individual file implements a module |
---|
4325 | \item |
---|
4326 | Case 2: Put the implementation of a module under the sub-directory, but there is only one file |
---|
4327 | \item |
---|
4328 | Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module |
---|
4329 | \item |
---|
4330 | Case 4: One file to express one aggregation |
---|
4331 | \item |
---|
4332 | Case 5: The file does not belong to any module; It is used for testing purpose |
---|
4333 | \end{itemize} |
---|
4334 | |
---|
4335 | The example only uses source code, ".do" files, to show the module file organization. |
---|
4336 | Other module packaging formats, like binary, must also follow the same rules. |
---|
4337 | |
---|
4338 | |
---|
4339 | \subsubsection{Module File Format} |
---|
4340 | |
---|
4341 | \CFA supports different types of module file formats. |
---|
4342 | |
---|
4343 | \begin{itemize} |
---|
4344 | \item |
---|
4345 | Pure source code format: The files should be organized following the previous section's definition. |
---|
4346 | \item |
---|
4347 | IR format (TBD): The \CFA compiler IR format, similar to the source code format |
---|
4348 | \item |
---|
4349 | Binary format, including ".a" static library or ".so" dynamic linkage library |
---|
4350 | \begin{itemize} |
---|
4351 | \item |
---|
4352 | The file's name must match the right level's module name defined in the previous section |
---|
4353 | \item |
---|
4354 | E.g. "util.so" includes all modules for the package util. |
---|
4355 | \item |
---|
4356 | E.g. "string.so" under the package directory to include files belonging to "module string;" |
---|
4357 | \end{itemize} |
---|
4358 | \item |
---|
4359 | Archive format |
---|
4360 | \begin{itemize} |
---|
4361 | \item |
---|
4362 | The archive is named as ".dar", and is a zip archive of the source code or the binary for a package |
---|
4363 | \item |
---|
4364 | E.g. "util.dar" is the whole package for util package including the package direction file |
---|
4365 | \end{itemize} |
---|
4366 | \item |
---|
4367 | Hybrid format |
---|
4368 | \begin{itemize} |
---|
4369 | \item |
---|
4370 | A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format |
---|
4371 | \item |
---|
4372 | The only limitation is that the names of the files must match the module location names defined in previous section |
---|
4373 | \end{itemize} |
---|
4374 | \end{itemize} |
---|
4375 | |
---|
4376 | |
---|
4377 | \subsection{Package and Module Locating} |
---|
4378 | |
---|
4379 | The 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. |
---|
4380 | If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries. |
---|
4381 | |
---|
4382 | When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order: |
---|
4383 | |
---|
4384 | \begin{enumerate} |
---|
4385 | \item |
---|
4386 | This source file's directory tree, which is typically the project's src directory |
---|
4387 | \item |
---|
4388 | All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory |
---|
4389 | \item |
---|
4390 | The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable |
---|
4391 | \item |
---|
4392 | The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory |
---|
4393 | \item |
---|
4394 | If 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 |
---|
4395 | \end{enumerate} |
---|
4396 | |
---|
4397 | The module found first in a package will shadow the modules with the same name in the later packages in the search sequence. |
---|
4398 | |
---|
4399 | |
---|
4400 | \subsubsection{Dependent Package} |
---|
4401 | |
---|
4402 | Dependent packages are those packages containing modules that the current project's source code will import from. |
---|
4403 | Dependent packages are defined implicitly or explicitly in one \CFA project. |
---|
4404 | All of the packages under the current project's pkg directory are implicitly dependent packages. |
---|
4405 | For others, the dependent packages must be defined in the project's Do.prj file. |
---|
4406 | |
---|
4407 | |
---|
4408 | \subsubsection{Package and Module Locating Example} |
---|
4409 | |
---|
4410 | \begin{cfa} |
---|
4411 | # A project's source code tree |
---|
4412 | |
---|
4413 | -------------------------------------- |
---|
4414 | |
---|
4415 | + testProject |
---|
4416 | Do.prj |
---|
4417 | + src |
---|
4418 | main.do |
---|
4419 | + pkg |
---|
4420 | + security-1.1 |
---|
4421 | Do.prj |
---|
4422 | security.do #module security |
---|
4423 | |
---|
4424 | -------------------------------------- |
---|
4425 | |
---|
4426 | # Do.prj |
---|
4427 | |
---|
4428 | -------------------------------------- |
---|
4429 | |
---|
4430 | [dependences] |
---|
4431 | std |
---|
4432 | util = "0.2" |
---|
4433 | |
---|
4434 | -------------------------------------- |
---|
4435 | |
---|
4436 | # main.do |
---|
4437 | |
---|
4438 | --------------------------------------- |
---|
4439 | |
---|
4440 | import security; |
---|
4441 | import std/vector; |
---|
4442 | import container; |
---|
4443 | |
---|
4444 | ---------------------------------------- |
---|
4445 | \end{cfa} |
---|
4446 | |
---|
4447 | |
---|
4448 | \begin{cfa} |
---|
4449 | # pkg directory's source code tree |
---|
4450 | |
---|
4451 | ----------------------------------------- |
---|
4452 | |
---|
4453 | + pkg |
---|
4454 | + std-1.0 |
---|
4455 | Do.prj |
---|
4456 | vector.do #module std/vector; |
---|
4457 | queue.do #module std/queue; |
---|
4458 | + std-1.1 |
---|
4459 | Do.prj |
---|
4460 | vector.do #module std/vector; |
---|
4461 | queue.do #module std/queue; |
---|
4462 | list.do #module std/list; |
---|
4463 | + util-0.1 |
---|
4464 | Do.prj |
---|
4465 | container.do #module container; |
---|
4466 | + security-1.0 |
---|
4467 | security.do #module security; |
---|
4468 | ------------------------------------------ |
---|
4469 | \end{cfa} |
---|
4470 | |
---|
4471 | |
---|
4472 | During the compiling of main.do file import security; |
---|
4473 | The security module appears in both the local security-1.1 package, and the global security-1.0 package. |
---|
4474 | According to the locating sequence, the local security module in security-1.1 will be used. |
---|
4475 | And because the security-1.1 package is under local's pkg directory. |
---|
4476 | No dependence description is required in the project Do.prj file. |
---|
4477 | |
---|
4478 | import std/vector; |
---|
4479 | |
---|
4480 | The 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. |
---|
4481 | |
---|
4482 | import container; |
---|
4483 | |
---|
4484 | The 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. |
---|
4485 | The builder tool then will try to retrieve it from the web and store it in the global pkg directory. |
---|
4486 | After that, the container module from the newly downloaded package will be used in the compilation. |
---|
4487 | \end{comment} |
---|
4488 | |
---|
4489 | |
---|
4490 | \section{Comparison with Other Languages} |
---|
4491 | |
---|
4492 | \CFA is one of many languages that attempts to improve upon C. |
---|
4493 | In developing \CFA, many other languages were consulted for ideas, constructs, and syntax. |
---|
4494 | Therefore, it is important to show how these languages each compare with Do. |
---|
4495 | In this section, \CFA is compared with what the writers of this document consider to be the closest competitors of Do: \Index*[C++]{\CC{}}, \Index*{Go}, \Index*{Rust}, and \Index*{D}. |
---|
4496 | |
---|
4497 | |
---|
4498 | \begin{comment} |
---|
4499 | \subsection[Comparing Key Features of CFA]{Comparing Key Features of \CFA} |
---|
4500 | |
---|
4501 | |
---|
4502 | {% local change to lstlising to reduce font size |
---|
4503 | |
---|
4504 | |
---|
4505 | \lstset{basicstyle=\linespread{0.9}\sf\relsize{-2}} |
---|
4506 | |
---|
4507 | |
---|
4508 | \subsubsection{Constructors and Destructors} |
---|
4509 | |
---|
4510 | \begin{flushleft} |
---|
4511 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4512 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4513 | \hline |
---|
4514 | \begin{cfa} |
---|
4515 | struct Line { |
---|
4516 | float lnth; |
---|
4517 | } |
---|
4518 | // default constructor |
---|
4519 | void ?{}( Line * l ) { |
---|
4520 | l->lnth = 0.0; |
---|
4521 | sout | "default" | endl; |
---|
4522 | } |
---|
4523 | |
---|
4524 | |
---|
4525 | // constructor with length |
---|
4526 | void ?{}( Line * l, float lnth ) { |
---|
4527 | l->lnth = lnth; |
---|
4528 | sout | "lnth" | l->lnth | endl; |
---|
4529 | |
---|
4530 | } |
---|
4531 | |
---|
4532 | // destructor |
---|
4533 | void ^?() { |
---|
4534 | sout | "destroyed" | endl; |
---|
4535 | l.lnth = 0.0; |
---|
4536 | } |
---|
4537 | |
---|
4538 | // usage |
---|
4539 | Line line1; |
---|
4540 | Line line2 = { 3.4 }; |
---|
4541 | \end{cfa} |
---|
4542 | & |
---|
4543 | \begin{lstlisting}[language=C++] |
---|
4544 | class Line { |
---|
4545 | float lnth; |
---|
4546 | |
---|
4547 | // default constructor |
---|
4548 | Line() { |
---|
4549 | cout << "default" << endl; |
---|
4550 | lnth = 0.0; |
---|
4551 | } |
---|
4552 | |
---|
4553 | |
---|
4554 | // constructor with lnth |
---|
4555 | Line( float l ) { |
---|
4556 | cout << "length " << length |
---|
4557 | << endl; |
---|
4558 | length = l; |
---|
4559 | } |
---|
4560 | |
---|
4561 | // destructor |
---|
4562 | ~Line() { |
---|
4563 | cout << "destroyed" << endl; |
---|
4564 | length = 0.0; |
---|
4565 | } |
---|
4566 | } |
---|
4567 | // usage |
---|
4568 | Line line1; |
---|
4569 | Line line2( 3.4 ); |
---|
4570 | \end{lstlisting} |
---|
4571 | & |
---|
4572 | \begin{lstlisting}[language=Golang] |
---|
4573 | type Line struct { |
---|
4574 | length float32 |
---|
4575 | } |
---|
4576 | // default constructor |
---|
4577 | func makeLine() Line { |
---|
4578 | fmt.PrintLn( "default" ) |
---|
4579 | return Line{0.0} |
---|
4580 | } |
---|
4581 | |
---|
4582 | |
---|
4583 | // constructor with length |
---|
4584 | func makeLine( length float32 ) Line { |
---|
4585 | fmt.Printf( "length %v", length ) |
---|
4586 | |
---|
4587 | return Line{length} |
---|
4588 | } |
---|
4589 | |
---|
4590 | // no destructor |
---|
4591 | |
---|
4592 | |
---|
4593 | |
---|
4594 | |
---|
4595 | |
---|
4596 | // usage |
---|
4597 | line1 := makeLine() |
---|
4598 | line2 := makeLine( 3.4 ) |
---|
4599 | \end{lstlisting} |
---|
4600 | & |
---|
4601 | \begin{cfa} |
---|
4602 | struct Line { |
---|
4603 | length: f32 |
---|
4604 | } |
---|
4605 | // default constructor |
---|
4606 | impl Default for Line { |
---|
4607 | fn default () -> Line { |
---|
4608 | println!( "default" ); |
---|
4609 | Line{ length: 0.0 } |
---|
4610 | } |
---|
4611 | } |
---|
4612 | // constructor with length |
---|
4613 | impl Line { |
---|
4614 | fn make( len: f32 ) -> Line { |
---|
4615 | println!( "length: {}", len ); |
---|
4616 | Line{ length: len } |
---|
4617 | } |
---|
4618 | } |
---|
4619 | // destructor |
---|
4620 | impl Drop for Line { |
---|
4621 | fn drop( &mut self ) { |
---|
4622 | self.length = 0.0 |
---|
4623 | } |
---|
4624 | } |
---|
4625 | // usage |
---|
4626 | let line1:Line = Default::default(); |
---|
4627 | Line line2( 3.4 ); |
---|
4628 | \end{cfa} |
---|
4629 | \end{tabular} |
---|
4630 | \end{flushleft} |
---|
4631 | |
---|
4632 | |
---|
4633 | \subsubsection{Operator Overloading} |
---|
4634 | |
---|
4635 | \begin{flushleft} |
---|
4636 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4637 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4638 | \hline |
---|
4639 | \begin{cfa} |
---|
4640 | struct Cpx { |
---|
4641 | double re, im; |
---|
4642 | }; |
---|
4643 | // overload addition operator |
---|
4644 | Cpx ?+?( Cpx l, const Cpx r ) { |
---|
4645 | return (Cpx){l.re+l.im, l.im+r.im}; |
---|
4646 | } |
---|
4647 | Cpx a, b, c; |
---|
4648 | c = a + b; |
---|
4649 | \end{cfa} |
---|
4650 | & |
---|
4651 | \begin{cfa} |
---|
4652 | struct Cpx { |
---|
4653 | double re, im; |
---|
4654 | }; |
---|
4655 | // overload addition operator |
---|
4656 | Cpx operator+( Cpx l, const Cpx r ) { |
---|
4657 | return (Cpx){l.re+l.im, l.im+r.im}; |
---|
4658 | } |
---|
4659 | Cpx a, b, c; |
---|
4660 | c = a + b; |
---|
4661 | \end{cfa} |
---|
4662 | & |
---|
4663 | \begin{cfa} |
---|
4664 | // no operator overloading |
---|
4665 | |
---|
4666 | |
---|
4667 | |
---|
4668 | |
---|
4669 | |
---|
4670 | |
---|
4671 | |
---|
4672 | \end{cfa} |
---|
4673 | & |
---|
4674 | \begin{cfa} |
---|
4675 | struct Cpx { |
---|
4676 | re: f32, |
---|
4677 | im: f32 |
---|
4678 | } |
---|
4679 | // overload addition operator |
---|
4680 | impl Add for Cpx { |
---|
4681 | type Output = Cpx |
---|
4682 | fn add(self, r: Cpx) -> Cpx { |
---|
4683 | let mut res = Cpx{re: 0.0, im: 0.0}; |
---|
4684 | res.re = self.re + r.re; |
---|
4685 | res.im = self.im + r.im; |
---|
4686 | return res |
---|
4687 | } |
---|
4688 | } |
---|
4689 | let (a, b, mut c) = ...; |
---|
4690 | c = a + b |
---|
4691 | \end{cfa} |
---|
4692 | \end{tabular} |
---|
4693 | \end{flushleft} |
---|
4694 | |
---|
4695 | |
---|
4696 | \subsubsection{Calling C Functions} |
---|
4697 | |
---|
4698 | \begin{flushleft} |
---|
4699 | \begin{tabular}{@{}l|l|l@{}} |
---|
4700 | \multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4701 | \hline |
---|
4702 | \begin{cfa}[boxpos=t] |
---|
4703 | extern "C" { |
---|
4704 | #include <sys/types.h> |
---|
4705 | #include <sys/stat.h> |
---|
4706 | #include <unistd.h> |
---|
4707 | } |
---|
4708 | size_t fileSize( const char *path ) { |
---|
4709 | struct stat s; |
---|
4710 | stat(path, &s); |
---|
4711 | return s.st_size; |
---|
4712 | } |
---|
4713 | \end{cfa} |
---|
4714 | & |
---|
4715 | \begin{cfa}[boxpos=t] |
---|
4716 | /* |
---|
4717 | #cgo |
---|
4718 | #include <sys/types.h> |
---|
4719 | #include <sys/stat.h> |
---|
4720 | #include <unistd.h> |
---|
4721 | */ |
---|
4722 | import "C" |
---|
4723 | import "unsafe" |
---|
4724 | |
---|
4725 | func fileSize(path string) C.size_t { |
---|
4726 | var buf C.struct_stat |
---|
4727 | c_string := C.CString(path) |
---|
4728 | C.stat(p, &buf) |
---|
4729 | C.free(unsafe.Pointer(c_string)) |
---|
4730 | return buf._st_size |
---|
4731 | } |
---|
4732 | \end{cfa} |
---|
4733 | & |
---|
4734 | \begin{cfa}[boxpos=t] |
---|
4735 | use libc::{c_int, size_t}; |
---|
4736 | // translated from sys/stat.h |
---|
4737 | #[repr(C)] |
---|
4738 | struct stat_t { |
---|
4739 | ... |
---|
4740 | st_size: size_t, |
---|
4741 | ... |
---|
4742 | } |
---|
4743 | #[link(name = "libc")] |
---|
4744 | extern { |
---|
4745 | fn stat(path: *const u8, |
---|
4746 | buf: *mut stat_t) -> c_int; |
---|
4747 | } |
---|
4748 | fn fileSize(path: *const u8) -> size_t |
---|
4749 | { |
---|
4750 | unsafe { |
---|
4751 | let mut buf: stat_t = uninit(); |
---|
4752 | stat(path, &mut buf); |
---|
4753 | buf.st_size |
---|
4754 | } |
---|
4755 | } |
---|
4756 | \end{cfa} |
---|
4757 | \end{tabular} |
---|
4758 | \end{flushleft} |
---|
4759 | |
---|
4760 | |
---|
4761 | \subsubsection{Generic Functions} |
---|
4762 | |
---|
4763 | \begin{flushleft} |
---|
4764 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4765 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4766 | \hline |
---|
4767 | \begin{cfa} |
---|
4768 | generic(type T, type N | |
---|
4769 | { int ?<?(N, N); }) |
---|
4770 | T *maximize(N (*f)(const T&), |
---|
4771 | int n, T *a) { |
---|
4772 | T *bestX = NULL; |
---|
4773 | N bestN; |
---|
4774 | for (int i = 0; i < n; i++) { |
---|
4775 | N curN = f(a[i]); |
---|
4776 | if (bestX == NULL || |
---|
4777 | curN > bestN) { |
---|
4778 | bestX = &a[i]; bestN = curN; |
---|
4779 | } |
---|
4780 | } |
---|
4781 | return bestX; |
---|
4782 | } |
---|
4783 | |
---|
4784 | string *longest(int n, string *p) |
---|
4785 | { |
---|
4786 | return maximize(length, n, p); |
---|
4787 | } |
---|
4788 | \end{cfa} |
---|
4789 | & |
---|
4790 | \begin{cfa} |
---|
4791 | template<typename T, typename F> |
---|
4792 | T *maximize(const F &f, |
---|
4793 | int n, T *a) { |
---|
4794 | typedef decltype(f(a[0])) N; |
---|
4795 | T *bestX = NULL; |
---|
4796 | N bestN; |
---|
4797 | for (int i = 0; i < n; i++) { |
---|
4798 | N curN = f(a[i]); |
---|
4799 | if (bestX == NULL || curN > bestN) |
---|
4800 | { |
---|
4801 | bestX = &a[i]; bestN = curN; |
---|
4802 | } |
---|
4803 | } |
---|
4804 | return bestX; |
---|
4805 | } |
---|
4806 | |
---|
4807 | string *longest(int n, string *p) { |
---|
4808 | return maximize( |
---|
4809 | [](const string &s) { |
---|
4810 | return s.length(); |
---|
4811 | }, n, p); |
---|
4812 | } |
---|
4813 | \end{cfa} |
---|
4814 | & |
---|
4815 | \begin{cfa} |
---|
4816 | // Go does not support generics! |
---|
4817 | func maximize( |
---|
4818 | gt func(interface{}, interface{}) bool, |
---|
4819 | f func(interface{}) interface{}, |
---|
4820 | a []interface{}) interface{} { |
---|
4821 | var bestX interface{} = nil |
---|
4822 | var bestN interface{} = nil |
---|
4823 | for _, x := range a { |
---|
4824 | curN := f(x) |
---|
4825 | if bestX == nil || gt(curN, bestN) |
---|
4826 | { |
---|
4827 | bestN = curN |
---|
4828 | bestX = x |
---|
4829 | } |
---|
4830 | } |
---|
4831 | return bestX |
---|
4832 | } |
---|
4833 | |
---|
4834 | func longest( |
---|
4835 | a []interface{}) interface{} { |
---|
4836 | return maximize( |
---|
4837 | func(a, b interface{}) bool { |
---|
4838 | return a.(int) > b.(int) }, |
---|
4839 | func(s interface{}) interface{} { |
---|
4840 | return len(s.(string)) }, |
---|
4841 | a).(string) |
---|
4842 | } |
---|
4843 | \end{cfa} |
---|
4844 | & |
---|
4845 | \begin{cfa} |
---|
4846 | use std::cmp::Ordering; |
---|
4847 | |
---|
4848 | fn maximize<N: Ord + Copy, T, F: |
---|
4849 | Fn(&T) -> N>(f: F, a: &Vec<T>) -> |
---|
4850 | Option<&T> { |
---|
4851 | let mut best_x: Option<&T> = None; |
---|
4852 | let mut best_n: Option<N> = None; |
---|
4853 | for x in a { |
---|
4854 | let n = f(x); |
---|
4855 | if (match best_n { None => true, |
---|
4856 | Some(bn) => |
---|
4857 | n.cmp(&bn) == Ordering::Greater }) |
---|
4858 | { |
---|
4859 | best_x = Some(x); |
---|
4860 | best_n = Some(n); |
---|
4861 | } |
---|
4862 | } |
---|
4863 | return best_x |
---|
4864 | } |
---|
4865 | |
---|
4866 | fn longest(a: &Vec<String>) -> |
---|
4867 | Option<&String> { |
---|
4868 | return |
---|
4869 | maximize(|x: &String| x.len(), a) |
---|
4870 | } |
---|
4871 | \end{cfa} |
---|
4872 | \end{tabular} |
---|
4873 | \end{flushleft} |
---|
4874 | |
---|
4875 | |
---|
4876 | \subsubsection{Modules / Packages} |
---|
4877 | |
---|
4878 | \begin{cfa} |
---|
4879 | \CFA |
---|
4880 | \CC |
---|
4881 | |
---|
4882 | |
---|
4883 | module example/M; |
---|
4884 | |
---|
4885 | export int inc(int val) { |
---|
4886 | return val + 1; |
---|
4887 | } |
---|
4888 | |
---|
4889 | |
---|
4890 | |
---|
4891 | |
---|
4892 | -------------------------------------- |
---|
4893 | //Use the module in another file |
---|
4894 | import example/M; |
---|
4895 | int main() { |
---|
4896 | print(M.inc(100)); |
---|
4897 | return 0; |
---|
4898 | } |
---|
4899 | // Using \CC17 module proposal |
---|
4900 | |
---|
4901 | module example.M; |
---|
4902 | |
---|
4903 | export { |
---|
4904 | int inc(int val); |
---|
4905 | } |
---|
4906 | |
---|
4907 | int inc(inv val) { |
---|
4908 | return val + 1; |
---|
4909 | } |
---|
4910 | -------------------------------------- |
---|
4911 | // Use the module in another file |
---|
4912 | import example.M; |
---|
4913 | int main() { |
---|
4914 | cout << inc(100) << endl; |
---|
4915 | return 0; |
---|
4916 | } |
---|
4917 | |
---|
4918 | Go |
---|
4919 | Rust |
---|
4920 | package example/M; |
---|
4921 | |
---|
4922 | func Inc(val int32) int32 { |
---|
4923 | // Capitalization indicates exported |
---|
4924 | return val + 100 |
---|
4925 | } |
---|
4926 | |
---|
4927 | |
---|
4928 | -------------------------------------- |
---|
4929 | //Use the package in another file |
---|
4930 | package main |
---|
4931 | import .fmt. |
---|
4932 | import "example/M" |
---|
4933 | |
---|
4934 | func main() int32 { |
---|
4935 | fmt.Printf(.%v., M.Inc(100)) |
---|
4936 | } |
---|
4937 | pub mod example { |
---|
4938 | pub mod M { |
---|
4939 | pub inc(val i32) -> i32 { |
---|
4940 | return val + 100; |
---|
4941 | } |
---|
4942 | } |
---|
4943 | } |
---|
4944 | |
---|
4945 | -------------------------------------- |
---|
4946 | //Use the module in another file |
---|
4947 | use example::M; |
---|
4948 | |
---|
4949 | |
---|
4950 | |
---|
4951 | fn main() { |
---|
4952 | println!(.{}., M::inc(100)); |
---|
4953 | } |
---|
4954 | \end{cfa} |
---|
4955 | |
---|
4956 | |
---|
4957 | \subsubsection{Parallel Tasks} |
---|
4958 | |
---|
4959 | \begin{flushleft} |
---|
4960 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4961 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4962 | \hline |
---|
4963 | \begin{cfa} |
---|
4964 | task Nonzero { |
---|
4965 | int *data; |
---|
4966 | int start; |
---|
4967 | int end; |
---|
4968 | int* res; |
---|
4969 | }; |
---|
4970 | |
---|
4971 | void ?{}(Nonzero &a, int d[], int s, |
---|
4972 | int e, int* subres) { |
---|
4973 | // constructor |
---|
4974 | a.data = d; |
---|
4975 | a.start = s; |
---|
4976 | a.end = e; |
---|
4977 | a.res = subres; |
---|
4978 | } |
---|
4979 | |
---|
4980 | // implicitly spawn thread here |
---|
4981 | void ?()(NonzeroCounter &a) { |
---|
4982 | int i; |
---|
4983 | int nonzero = 0; |
---|
4984 | for (i=start; c<end; ++i) { |
---|
4985 | if(a.data[i]!=0){ nonzero++;} |
---|
4986 | } |
---|
4987 | *a.res = nonzero; |
---|
4988 | } |
---|
4989 | |
---|
4990 | int main() { |
---|
4991 | int sz = ... |
---|
4992 | int data[sz] = ...; |
---|
4993 | int r1 = 0, r2=0; |
---|
4994 | int res; |
---|
4995 | { // create a scope for Nonzero |
---|
4996 | Nonzero n1{data, 0, sz/2, &n1}; |
---|
4997 | Nonzero n2{data, sz/2, sz, &n2}; |
---|
4998 | n1();//spawn |
---|
4999 | n2();//spawn |
---|
5000 | } |
---|
5001 | res = r1+r2; |
---|
5002 | return res; |
---|
5003 | } |
---|
5004 | \end{cfa} |
---|
5005 | & |
---|
5006 | \begin{cfa} |
---|
5007 | #include <thread> |
---|
5008 | #include <mutex> |
---|
5009 | |
---|
5010 | std::mutex m; |
---|
5011 | |
---|
5012 | |
---|
5013 | |
---|
5014 | |
---|
5015 | |
---|
5016 | |
---|
5017 | |
---|
5018 | |
---|
5019 | |
---|
5020 | |
---|
5021 | |
---|
5022 | |
---|
5023 | void task(const vector<int>&v, |
---|
5024 | int* res, size_t s, |
---|
5025 | size_t e) { |
---|
5026 | int non_zero = 0; |
---|
5027 | for(size_t i = s; i < e; ++i){ |
---|
5028 | if(v[i]!=0) { non_zero++;} |
---|
5029 | } |
---|
5030 | std::unique_lock<mutex> lck {m}; |
---|
5031 | *res += non_zero; |
---|
5032 | } |
---|
5033 | |
---|
5034 | int main() { |
---|
5035 | vector<int> data = ...; //data |
---|
5036 | int res = 0; |
---|
5037 | std::thread t1 {task, ref(data), |
---|
5038 | &res, 0, |
---|
5039 | data.size()/2}; |
---|
5040 | std::thread t2 {task, ref(data), |
---|
5041 | &res, data.size()/2, |
---|
5042 | data.size()}; |
---|
5043 | t1.join(); |
---|
5044 | t2.join(); |
---|
5045 | return res; |
---|
5046 | } |
---|
5047 | \end{cfa} |
---|
5048 | & |
---|
5049 | \begin{cfa} |
---|
5050 | package main |
---|
5051 | |
---|
5052 | import "fmt" |
---|
5053 | |
---|
5054 | func nonzero(data []int, c chan int) { |
---|
5055 | nz := 0 |
---|
5056 | for _, v:=range data { |
---|
5057 | if(v!=0) { nz := nz+1 } |
---|
5058 | } |
---|
5059 | c <- nz |
---|
5060 | } |
---|
5061 | |
---|
5062 | func main() { |
---|
5063 | sz := ... |
---|
5064 | data := make([]int, sz) |
---|
5065 | ... // data init |
---|
5066 | go nonzero(data[:len(data)/2], c) |
---|
5067 | go nonzero(data[len(data)/2:], c) |
---|
5068 | n1, n2 := <-c, <-c |
---|
5069 | res := n1 + n2 |
---|
5070 | fmt.Println(res) |
---|
5071 | } |
---|
5072 | \end{cfa} |
---|
5073 | & |
---|
5074 | \begin{cfa} |
---|
5075 | use std::thread; |
---|
5076 | use std::sync:mpsc::channel; |
---|
5077 | |
---|
5078 | fn main() { |
---|
5079 | let sz = ...; |
---|
5080 | let mut data:Vec<i32> = |
---|
5081 | Vec::with_capacity(sz as usize); |
---|
5082 | ... //init data |
---|
5083 | let (tx, rx) = channel(); |
---|
5084 | for i in 0..1 { |
---|
5085 | let tx = tx.clone(); |
---|
5086 | let data = data.clone() |
---|
5087 | thread::spawn(move|| { |
---|
5088 | let mut nz := 0; |
---|
5089 | let mut s = 0; |
---|
5090 | let mut e = sz / 2; |
---|
5091 | if i == 1 { |
---|
5092 | s = sz/2; |
---|
5093 | e = data.len(); |
---|
5094 | } |
---|
5095 | for i in s..(e - 1) { |
---|
5096 | if data[i] != 0 ( |
---|
5097 | nz = nz + 1 |
---|
5098 | } |
---|
5099 | } |
---|
5100 | tx.send(nz).unwrap(); |
---|
5101 | }); |
---|
5102 | } |
---|
5103 | let res = rx.recv().unwrap() + |
---|
5104 | rx.recv().unwrap(); |
---|
5105 | println!(.{}., res); |
---|
5106 | } |
---|
5107 | \end{cfa} |
---|
5108 | \end{tabular} |
---|
5109 | \end{flushleft} |
---|
5110 | |
---|
5111 | }% local change to lstlising to reduce font size |
---|
5112 | |
---|
5113 | |
---|
5114 | \subsection{Summary of Language Comparison} |
---|
5115 | \end{comment} |
---|
5116 | |
---|
5117 | |
---|
5118 | \subsection[C++]{\CC} |
---|
5119 | |
---|
5120 | \Index*[C++]{\CC{}} is a general-purpose programming language. |
---|
5121 | It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia) |
---|
5122 | |
---|
5123 | The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do. |
---|
5124 | \CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data. |
---|
5125 | \CFA uses modules instead to perform these same tasks. |
---|
5126 | Classes in \CC also enable inheritance among types. |
---|
5127 | Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility. |
---|
5128 | There are many studies and articles comparing inheritance and composition (or is-a versus has-a relationships), so we will not go into more detail here (Venners, 1998) (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering , 2012). |
---|
5129 | |
---|
5130 | Overloading 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. |
---|
5131 | References and exceptions in \CFA are heavily based on the same features from \CC. |
---|
5132 | The mechanism for interoperating with C code in \CFA is also borrowed from \CC. |
---|
5133 | |
---|
5134 | Both \CFA and \CC provide generics, and the syntax is quite similar. |
---|
5135 | The 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. |
---|
5136 | This means that a generic function can be defined in a compiled library, and still be used as expected from source. |
---|
5137 | |
---|
5138 | |
---|
5139 | \subsection{Go} |
---|
5140 | |
---|
5141 | \Index*{Go}, also commonly referred to as golang, is a programming language developed at Google in 2007 [.]. |
---|
5142 | It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type |
---|
5143 | safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia) |
---|
5144 | |
---|
5145 | Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned. |
---|
5146 | Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction. |
---|
5147 | Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse. |
---|
5148 | Both 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. |
---|
5149 | |
---|
5150 | Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks. |
---|
5151 | \CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection. |
---|
5152 | This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead. |
---|
5153 | |
---|
5154 | |
---|
5155 | \subsection{Rust} |
---|
5156 | |
---|
5157 | \Index*{Rust} is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research. |
---|
5158 | It is designed to be a "safe, concurrent, practical language", supporting pure-functional, concurrent-actor[dubious . discuss][citation needed], imperative-procedural, and object-oriented styles. |
---|
5159 | |
---|
5160 | The primary focus of Rust is in safety, especially in concurrent programs. |
---|
5161 | To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety. |
---|
5162 | This safety comes at the cost of a difficult learning curve, a change in the thought model of the program, and often some runtime overhead. |
---|
5163 | |
---|
5164 | Aside from those key differences, Rust and \CFA also have several similarities. |
---|
5165 | Both languages support no overhead interoperability with C and have minimal runtimes. |
---|
5166 | Both languages support inheritance and polymorphism through the use of interfaces (traits). |
---|
5167 | |
---|
5168 | |
---|
5169 | \subsection{D} |
---|
5170 | |
---|
5171 | The \Index*{D} programming language is an object-oriented, imperative, multi-paradigm system programming |
---|
5172 | language created by Walter Bright of Digital Mars and released in 2001. [.] |
---|
5173 | Though it originated as a re-engineering of \CC, D is a distinct language, having redesigned some core \CC features while also taking inspiration from other languages, notably \Index*{Java}, \Index*{Python}, Ruby, C\#, and Eiffel. |
---|
5174 | |
---|
5175 | D and \CFA both start with C and add productivity features. |
---|
5176 | The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces. |
---|
5177 | D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces. |
---|
5178 | Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates. |
---|
5179 | D does not have any built-in concurrency constructs in the |
---|
5180 | language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency. |
---|
5181 | |
---|
5182 | |
---|
5183 | \appendix |
---|
5184 | |
---|
5185 | |
---|
5186 | \section{Syntax Ambiguities} |
---|
5187 | |
---|
5188 | C has a number of syntax ambiguities, which are resolved by taking the longest sequence of overlapping characters that constitute a token. |
---|
5189 | For example, the program fragment ©x+++++y© is parsed as \lstinline[showspaces=true]@x ++ ++ + y@ because operator tokens ©++© and ©+© overlap. |
---|
5190 | Unfortunately, the longest sequence violates a constraint on increment operators, even though the parse \lstinline[showspaces=true]@x ++ + ++ y@ might yield a correct expression. |
---|
5191 | Hence, C programmers are aware that spaces have to added to disambiguate certain syntactic cases. |
---|
5192 | |
---|
5193 | In \CFA, there are ambiguous cases with dereference and operator identifiers, \eg ©int *?*?()©, where the string ©*?*?© can be interpreted as: |
---|
5194 | \begin{cfa} |
---|
5195 | *?§\color{red}\textvisiblespace§*? §\C{// dereference operator, dereference operator}§ |
---|
5196 | *§\color{red}\textvisiblespace§?*? §\C{// dereference, multiplication operator}§ |
---|
5197 | \end{cfa} |
---|
5198 | By default, the first interpretation is selected, which does not yield a meaningful parse. |
---|
5199 | Therefore, \CFA does a lexical look-ahead for the second case, and backtracks to return the leading unary operator and reparses the trailing operator identifier. |
---|
5200 | Otherwise a space is needed between the unary operator and operator identifier to disambiguate this common case. |
---|
5201 | |
---|
5202 | A similar issue occurs with the dereference, ©*?(...)©, and routine-call, ©?()(...)© identifiers. |
---|
5203 | The ambiguity occurs when the deference operator has no parameters: |
---|
5204 | \begin{cfa} |
---|
5205 | *?()§\color{red}\textvisiblespace...§ ; |
---|
5206 | *?()§\color{red}\textvisiblespace...§(...) ; |
---|
5207 | \end{cfa} |
---|
5208 | requiring arbitrary whitespace look-ahead for the routine-call parameter-list to disambiguate. |
---|
5209 | However, the dereference operator \emph{must} have a parameter/argument to dereference ©*?(...)©. |
---|
5210 | Hence, always interpreting the string ©*?()© as \lstinline[showspaces=true]@* ?()@ does not preclude any meaningful program. |
---|
5211 | |
---|
5212 | The remaining cases are with the increment/decrement operators and conditional expression, \eg: |
---|
5213 | \begin{cfa} |
---|
5214 | i++?§\color{red}\textvisiblespace...§(...); |
---|
5215 | i?++§\color{red}\textvisiblespace...§(...); |
---|
5216 | \end{cfa} |
---|
5217 | requiring arbitrary whitespace look-ahead for the operator parameter-list, even though that interpretation is an incorrect expression (juxtaposed identifiers). |
---|
5218 | Therefore, it is necessary to disambiguate these cases with a space: |
---|
5219 | \begin{cfa} |
---|
5220 | i++§\color{red}\textvisiblespace§? i : 0; |
---|
5221 | i?§\color{red}\textvisiblespace§++i : 0; |
---|
5222 | \end{cfa} |
---|
5223 | |
---|
5224 | |
---|
5225 | \section{\CFA Keywords} |
---|
5226 | \label{s:CFAKeywords} |
---|
5227 | |
---|
5228 | \begin{quote2} |
---|
5229 | \begin{tabular}{llll} |
---|
5230 | \begin{tabular}{@{}l@{}} |
---|
5231 | ©_AT© \\ |
---|
5232 | ©catch© \\ |
---|
5233 | ©catchResume© \\ |
---|
5234 | ©choose© \\ |
---|
5235 | ©coroutine© \\ |
---|
5236 | ©disable© \\ |
---|
5237 | \end{tabular} |
---|
5238 | & |
---|
5239 | \begin{tabular}{@{}l@{}} |
---|
5240 | ©dtype© \\ |
---|
5241 | ©enable© \\ |
---|
5242 | ©fallthrough© \\ |
---|
5243 | ©fallthru© \\ |
---|
5244 | ©finally© \\ |
---|
5245 | ©forall© \\ |
---|
5246 | \end{tabular} |
---|
5247 | & |
---|
5248 | \begin{tabular}{@{}l@{}} |
---|
5249 | ©ftype© \\ |
---|
5250 | ©lvalue© \\ |
---|
5251 | ©monitor© \\ |
---|
5252 | ©mutex© \\ |
---|
5253 | ©one_t© \\ |
---|
5254 | ©otype© \\ |
---|
5255 | \end{tabular} |
---|
5256 | & |
---|
5257 | \begin{tabular}{@{}l@{}} |
---|
5258 | ©throw© \\ |
---|
5259 | ©throwResume© \\ |
---|
5260 | ©trait© \\ |
---|
5261 | ©try© \\ |
---|
5262 | ©ttype© \\ |
---|
5263 | ©zero_t© \\ |
---|
5264 | \end{tabular} |
---|
5265 | \end{tabular} |
---|
5266 | \end{quote2} |
---|
5267 | |
---|
5268 | |
---|
5269 | \section{Incompatible} |
---|
5270 | |
---|
5271 | The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{C++14}. |
---|
5272 | |
---|
5273 | |
---|
5274 | \begin{enumerate} |
---|
5275 | \item |
---|
5276 | \begin{description} |
---|
5277 | \item[Change:] add new keywords \\ |
---|
5278 | New keywords are added to \CFA (see~\VRef{s:CFAKeywords}). |
---|
5279 | \item[Rationale:] keywords added to implement new semantics of \CFA. |
---|
5280 | \item[Effect on original feature:] change to semantics of well-defined feature. \\ |
---|
5281 | Any \Celeven programs using these keywords as identifiers are invalid \CFA programs. |
---|
5282 | \item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism (see~\VRef{s:BackquoteIdentifiers}). |
---|
5283 | \item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare. |
---|
5284 | \end{description} |
---|
5285 | |
---|
5286 | \item |
---|
5287 | \begin{description} |
---|
5288 | \item[Change:] drop K\&R C declarations \\ |
---|
5289 | K\&R declarations allow an implicit base-type of ©int©, if no type is specified, plus an alternate syntax for declaring parameters. |
---|
5290 | \eg: |
---|
5291 | \begin{cfa} |
---|
5292 | x; §\C{// int x}§ |
---|
5293 | *y; §\C{// int *y}§ |
---|
5294 | f( p1, p2 ); §\C{// int f( int p1, int p2 );}§ |
---|
5295 | g( p1, p2 ) int p1, p2; §\C{// int g( int p1, int p2 );}§ |
---|
5296 | \end{cfa} |
---|
5297 | \CFA supports K\&R routine definitions: |
---|
5298 | \begin{cfa} |
---|
5299 | f( a, b, c ) §\C{// default int return}§ |
---|
5300 | int a, b; char c §\C{// K\&R parameter declarations}§ |
---|
5301 | { |
---|
5302 | ... |
---|
5303 | } |
---|
5304 | \end{cfa} |
---|
5305 | \item[Rationale:] dropped from \Celeven standard.\footnote{ |
---|
5306 | At 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}} |
---|
5307 | \item[Effect on original feature:] original feature is deprecated. \\ |
---|
5308 | Any old C programs using these K\&R declarations are invalid \CFA programs. |
---|
5309 | \item[Difficulty of converting:] trivial to convert to \CFA. |
---|
5310 | \item[How widely used:] existing usages are rare. |
---|
5311 | \end{description} |
---|
5312 | |
---|
5313 | \item |
---|
5314 | \begin{description} |
---|
5315 | \item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading: |
---|
5316 | \begin{cfa} |
---|
5317 | int rtn( int i ); |
---|
5318 | int rtn( char c ); |
---|
5319 | rtn( 'x' ); §\C{// programmer expects 2nd rtn to be called}§ |
---|
5320 | \end{cfa} |
---|
5321 | \item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first. |
---|
5322 | In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character. |
---|
5323 | \begin{cfa} |
---|
5324 | sout | 'x' | " " | (int)'x' | endl; |
---|
5325 | x 120 |
---|
5326 | \end{cfa} |
---|
5327 | Having to cast ©'x'© to ©char© is non-intuitive. |
---|
5328 | \item[Effect on original feature:] change to semantics of well-defined feature that depend on: |
---|
5329 | \begin{cfa} |
---|
5330 | sizeof( 'x' ) == sizeof( int ) |
---|
5331 | \end{cfa} |
---|
5332 | no long work the same in \CFA programs. |
---|
5333 | \item[Difficulty of converting:] simple |
---|
5334 | \item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©. |
---|
5335 | \end{description} |
---|
5336 | |
---|
5337 | \item |
---|
5338 | \begin{description} |
---|
5339 | \item[Change:] make string literals ©const©: |
---|
5340 | \begin{cfa} |
---|
5341 | char * p = "abc"; §\C{// valid in C, deprecated in \CFA}§ |
---|
5342 | char * q = expr ? "abc" : "de"; §\C{// valid in C, invalid in \CFA}§ |
---|
5343 | \end{cfa} |
---|
5344 | The type of a string literal is changed from ©[] char© to ©const [] char©. |
---|
5345 | Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©. |
---|
5346 | \item[Rationale:] This change is a safety issue: |
---|
5347 | \begin{cfa} |
---|
5348 | char * p = "abc"; |
---|
5349 | p[0] = 'w'; §\C{// segment fault or change constant literal}§ |
---|
5350 | \end{cfa} |
---|
5351 | The same problem occurs when passing a string literal to a routine that changes its argument. |
---|
5352 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5353 | \item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©. |
---|
5354 | \item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare. |
---|
5355 | \end{description} |
---|
5356 | |
---|
5357 | \item |
---|
5358 | \begin{description} |
---|
5359 | \item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope: |
---|
5360 | \begin{cfa} |
---|
5361 | int i; §\C{// forward definition}§ |
---|
5362 | int *j = ®&i®; §\C{// forward reference, valid in C, invalid in \CFA}§ |
---|
5363 | int i = 0; §\C{// definition}§ |
---|
5364 | \end{cfa} |
---|
5365 | is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed. |
---|
5366 | This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example, |
---|
5367 | \begin{cfa} |
---|
5368 | struct X { int i; struct X *next; }; |
---|
5369 | static struct X a; §\C{// forward definition}§ |
---|
5370 | static struct X b = { 0, ®&a® }; §\C{// forward reference, valid in C, invalid in \CFA}§ |
---|
5371 | static struct X a = { 1, &b }; §\C{// definition}§ |
---|
5372 | \end{cfa} |
---|
5373 | \item[Rationale:] avoids having different initialization rules for builtin types and user-defined types. |
---|
5374 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5375 | \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. |
---|
5376 | \item[How widely used:] seldom |
---|
5377 | \end{description} |
---|
5378 | |
---|
5379 | \item |
---|
5380 | \begin{description} |
---|
5381 | \item[Change:] have ©struct© introduce a scope for nested types: |
---|
5382 | \begin{cfa} |
---|
5383 | enum ®Colour® { R, G, B, Y, C, M }; |
---|
5384 | struct Person { |
---|
5385 | enum ®Colour® { R, G, B }; §\C{// nested type}§ |
---|
5386 | struct Face { §\C{// nested type}§ |
---|
5387 | ®Colour® Eyes, Hair; §\C{// type defined outside (1 level)}§ |
---|
5388 | }; |
---|
5389 | ®.Colour® shirt; §\C{// type defined outside (top level)}§ |
---|
5390 | ®Colour® pants; §\C{// type defined same level}§ |
---|
5391 | Face looks[10]; §\C{// type defined same level}§ |
---|
5392 | }; |
---|
5393 | ®Colour® c = R; §\C{// type/enum defined same level}§ |
---|
5394 | Person®.Colour® pc = Person®.®R; §\C{// type/enum defined inside}§ |
---|
5395 | Person®.®Face pretty; §\C{// type defined inside}§ |
---|
5396 | \end{cfa} |
---|
5397 | In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing structure, \ie the nested types are hoisted to the scope of the outer-most type, which is not useful and confusing. |
---|
5398 | \CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC{}}. |
---|
5399 | Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''. |
---|
5400 | \item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism. |
---|
5401 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5402 | \item[Difficulty of converting:] Semantic transformation. |
---|
5403 | \item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version. |
---|
5404 | \end{description} |
---|
5405 | |
---|
5406 | \item |
---|
5407 | \begin{description} |
---|
5408 | \item[Change:] In C++, the name of a nested class is local to its enclosing class. |
---|
5409 | \item[Rationale:] C++ classes have member functions which require that classes establish scopes. |
---|
5410 | \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: |
---|
5411 | \begin{cfa} |
---|
5412 | struct Y; §\C{// struct Y and struct X are at the same scope}§ |
---|
5413 | struct X { |
---|
5414 | struct Y { /* ... */ } y; |
---|
5415 | }; |
---|
5416 | \end{cfa} |
---|
5417 | All 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. |
---|
5418 | Note: this is a consequence of the difference in scope rules, which is documented in 3.3. |
---|
5419 | \item[How widely used:] Seldom. |
---|
5420 | \end{description} |
---|
5421 | |
---|
5422 | \item |
---|
5423 | \begin{description} |
---|
5424 | \item[Change:] comma expression is disallowed as subscript |
---|
5425 | \item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new style arrays. |
---|
5426 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5427 | \item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]© |
---|
5428 | \item[How widely used:] seldom. |
---|
5429 | \end{description} |
---|
5430 | \end{enumerate} |
---|
5431 | |
---|
5432 | |
---|
5433 | \section{Standard Headers} |
---|
5434 | \label{s:StandardHeaders} |
---|
5435 | |
---|
5436 | \Celeven prescribes the following standard header-files~\cite[\S~7.1.2]{C11} and \CFA adds to this list: |
---|
5437 | \begin{quote2} |
---|
5438 | \lstset{deletekeywords={float}} |
---|
5439 | \begin{tabular}{@{}llll|l@{}} |
---|
5440 | \multicolumn{4}{c|}{C11} & \multicolumn{1}{c}{\CFA} \\ |
---|
5441 | \hline |
---|
5442 | \begin{tabular}{@{}l@{}} |
---|
5443 | \Indexc{assert.h} \\ |
---|
5444 | \Indexc{complex.h} \\ |
---|
5445 | \Indexc{ctype.h} \\ |
---|
5446 | \Indexc{errno.h} \\ |
---|
5447 | \Indexc{fenv.h} \\ |
---|
5448 | \Indexc{float.h} \\ |
---|
5449 | \Indexc{inttypes.h} \\ |
---|
5450 | \Indexc{iso646.h} \\ |
---|
5451 | \end{tabular} |
---|
5452 | & |
---|
5453 | \begin{tabular}{@{}l@{}} |
---|
5454 | \Indexc{limits.h} \\ |
---|
5455 | \Indexc{locale.h} \\ |
---|
5456 | \Indexc{math.h} \\ |
---|
5457 | \Indexc{setjmp.h} \\ |
---|
5458 | \Indexc{signal.h} \\ |
---|
5459 | \Indexc{stdalign.h} \\ |
---|
5460 | \Indexc{stdarg.h} \\ |
---|
5461 | \Indexc{stdatomic.h} \\ |
---|
5462 | \end{tabular} |
---|
5463 | & |
---|
5464 | \begin{tabular}{@{}l@{}} |
---|
5465 | \Indexc{stdbool.h} \\ |
---|
5466 | \Indexc{stddef.h} \\ |
---|
5467 | \Indexc{stdint.h} \\ |
---|
5468 | \Indexc{stdio.h} \\ |
---|
5469 | \Indexc{stdlib.h} \\ |
---|
5470 | \Indexc{stdnoreturn.h} \\ |
---|
5471 | \Indexc{string.h} \\ |
---|
5472 | \Indexc{tgmath.h} \\ |
---|
5473 | \end{tabular} |
---|
5474 | & |
---|
5475 | \begin{tabular}{@{}l@{}} |
---|
5476 | \Indexc{threads.h} \\ |
---|
5477 | \Indexc{time.h} \\ |
---|
5478 | \Indexc{uchar.h} \\ |
---|
5479 | \Indexc{wchar.h} \\ |
---|
5480 | \Indexc{wctype.h} \\ |
---|
5481 | \\ |
---|
5482 | \\ |
---|
5483 | \\ |
---|
5484 | \end{tabular} |
---|
5485 | & |
---|
5486 | \begin{tabular}{@{}l@{}} |
---|
5487 | \Indexc{unistd.h} \\ |
---|
5488 | \Indexc{gmp.h} \\ |
---|
5489 | \\ |
---|
5490 | \\ |
---|
5491 | \\ |
---|
5492 | \\ |
---|
5493 | \\ |
---|
5494 | \\ |
---|
5495 | \end{tabular} |
---|
5496 | \end{tabular} |
---|
5497 | \end{quote2} |
---|
5498 | For the prescribed head-files, \CFA uses header interposition to wraps these includes in an ©extern "C"©; |
---|
5499 | hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}). |
---|
5500 | All other C header files must be explicitly wrapped in ©extern "C"© to prevent name mangling. |
---|
5501 | For \Index*[C++]{\CC{}}, the name-mangling issue is handled implicitly because most C header-files are augmented with checks for preprocessor variable ©__cplusplus©, which adds appropriate ©extern "C"© qualifiers. |
---|
5502 | |
---|
5503 | |
---|
5504 | \section{Standard Library} |
---|
5505 | \label{s:StandardLibrary} |
---|
5506 | |
---|
5507 | The \CFA standard-library wraps explicitly-polymorphic C routines into implicitly-polymorphic versions. |
---|
5508 | |
---|
5509 | |
---|
5510 | \subsection{Storage Management} |
---|
5511 | |
---|
5512 | The storage-management routines extend their C equivalents by overloading, alternate names, providing shallow type-safety, and removing the need to specify the allocation size for non-array types. |
---|
5513 | |
---|
5514 | Storage management provides the following capabilities: |
---|
5515 | \begin{description} |
---|
5516 | \item[fill] |
---|
5517 | after allocation the storage is filled with a specified character. |
---|
5518 | \item[resize] |
---|
5519 | an existing allocation is decreased or increased in size. |
---|
5520 | In either case, new storage may or may not be allocated and, if there is a new allocation, as much data from the existing allocation is copied. |
---|
5521 | For an increase in storage size, new storage after the copied data may be filled. |
---|
5522 | \item[alignment] |
---|
5523 | an allocation starts on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes. |
---|
5524 | \item[array] |
---|
5525 | the allocation size is scaled to the specified number of array elements. |
---|
5526 | An array may be filled, resized, or aligned. |
---|
5527 | \end{description} |
---|
5528 | The table shows allocation routines supporting different combinations of storage-management capabilities: |
---|
5529 | \begin{center} |
---|
5530 | \begin{tabular}{@{}lr|l|l|l|l@{}} |
---|
5531 | & & \multicolumn{1}{c|}{fill} & resize & alignment & array \\ |
---|
5532 | \hline |
---|
5533 | C & ©malloc© & no & no & no & no \\ |
---|
5534 | & ©calloc© & yes (0 only) & no & no & yes \\ |
---|
5535 | & ©realloc© & no/copy & yes & no & no \\ |
---|
5536 | & ©memalign© & no & no & yes & no \\ |
---|
5537 | & ©posix_memalign© & no & no & yes & no \\ |
---|
5538 | C11 & ©aligned_alloc© & no & no & yes & no \\ |
---|
5539 | \CFA & ©alloc© & no/copy/yes & no/yes & no & yes \\ |
---|
5540 | & ©align_alloc© & no/yes & no & yes & yes \\ |
---|
5541 | \end{tabular} |
---|
5542 | \end{center} |
---|
5543 | It is impossible to resize with alignment because the underlying ©realloc© allocates storage if more space is needed, and it does not honour alignment from the original allocation. |
---|
5544 | |
---|
5545 | \leavevmode |
---|
5546 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5547 | // C unsafe allocation |
---|
5548 | extern "C" { |
---|
5549 | void * mallac( size_t size );§\indexc{memset}§ |
---|
5550 | void * calloc( size_t dim, size_t size );§\indexc{calloc}§ |
---|
5551 | void * realloc( void * ptr, size_t size );§\indexc{realloc}§ |
---|
5552 | void * memalign( size_t align, size_t size );§\indexc{memalign}§ |
---|
5553 | int posix_memalign( void ** ptr, size_t align, size_t size );§\indexc{posix_memalign}§ |
---|
5554 | } |
---|
5555 | |
---|
5556 | // §\CFA§ safe equivalents, i.e., implicit size specification |
---|
5557 | forall( dtype T | sized(T) ) T * malloc( void ); |
---|
5558 | forall( dtype T | sized(T) ) T * calloc( size_t dim ); |
---|
5559 | forall( dtype T | sized(T) ) T * realloc( T * ptr, size_t size ); |
---|
5560 | forall( dtype T | sized(T) ) T * memalign( size_t align ); |
---|
5561 | forall( dtype T | sized(T) ) T * aligned_alloc( size_t align ); |
---|
5562 | forall( dtype T | sized(T) ) int posix_memalign( T ** ptr, size_t align ); |
---|
5563 | |
---|
5564 | // §\CFA§ safe general allocation, fill, resize, array |
---|
5565 | forall( dtype T | sized(T) ) T * alloc( void );§\indexc{alloc}§ |
---|
5566 | forall( dtype T | sized(T) ) T * alloc( char fill ); |
---|
5567 | forall( dtype T | sized(T) ) T * alloc( size_t dim ); |
---|
5568 | forall( dtype T | sized(T) ) T * alloc( size_t dim, char fill ); |
---|
5569 | forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim ); |
---|
5570 | forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim, char fill ); |
---|
5571 | |
---|
5572 | // §\CFA§ safe general allocation, align, fill, array |
---|
5573 | forall( dtype T | sized(T) ) T * align_alloc( size_t align ); |
---|
5574 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, char fill ); |
---|
5575 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim ); |
---|
5576 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim, char fill ); |
---|
5577 | |
---|
5578 | // C unsafe initialization/copy |
---|
5579 | extern "C" { |
---|
5580 | void * memset( void * dest, int c, size_t size ); |
---|
5581 | void * memcpy( void * dest, const void * src, size_t size ); |
---|
5582 | } |
---|
5583 | |
---|
5584 | // §\CFA§ safe initialization/copy, i.e., implicit size specification |
---|
5585 | forall( dtype T | sized(T) ) T * memset( T * dest, char c );§\indexc{memset}§ |
---|
5586 | forall( dtype T | sized(T) ) T * memcpy( T * dest, const T * src );§\indexc{memcpy}§ |
---|
5587 | |
---|
5588 | // §\CFA§ safe initialization/copy array |
---|
5589 | forall( dtype T | sized(T) ) T * memset( T dest[], size_t dim, char c ); |
---|
5590 | forall( dtype T | sized(T) ) T * memcpy( T dest[], const T src[], size_t dim ); |
---|
5591 | |
---|
5592 | // §\CFA§ allocation/deallocation and constructor/destructor |
---|
5593 | forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * new( Params p );§\indexc{new}§ |
---|
5594 | forall( dtype T | { void ^?{}( T * ); } ) void delete( T * ptr );§\indexc{delete}§ |
---|
5595 | forall( dtype T, ttype Params | { void ^?{}( T * ); void delete( Params ); } ) |
---|
5596 | void delete( T * ptr, Params rest ); |
---|
5597 | |
---|
5598 | // §\CFA§ allocation/deallocation and constructor/destructor, array |
---|
5599 | forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * anew( size_t dim, Params p );§\indexc{anew}§ |
---|
5600 | forall( dtype T | sized(T) | { void ^?{}( T * ); } ) void adelete( size_t dim, T arr[] );§\indexc{adelete}§ |
---|
5601 | forall( dtype T | sized(T) | { void ^?{}( T * ); }, ttype Params | { void adelete( Params ); } ) |
---|
5602 | void adelete( size_t dim, T arr[], Params rest ); |
---|
5603 | \end{cfa} |
---|
5604 | |
---|
5605 | |
---|
5606 | \subsection{Conversion} |
---|
5607 | |
---|
5608 | \leavevmode |
---|
5609 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5610 | int ato( const char * ptr );§\indexc{ato}§ |
---|
5611 | unsigned int ato( const char * ptr ); |
---|
5612 | long int ato( const char * ptr ); |
---|
5613 | unsigned long int ato( const char * ptr ); |
---|
5614 | long long int ato( const char * ptr ); |
---|
5615 | unsigned long long int ato( const char * ptr ); |
---|
5616 | float ato( const char * ptr ); |
---|
5617 | double ato( const char * ptr ); |
---|
5618 | long double ato( const char * ptr ); |
---|
5619 | float _Complex ato( const char * ptr ); |
---|
5620 | double _Complex ato( const char * ptr ); |
---|
5621 | long double _Complex ato( const char * ptr ); |
---|
5622 | |
---|
5623 | int strto( const char * sptr, char ** eptr, int base ); |
---|
5624 | unsigned int strto( const char * sptr, char ** eptr, int base ); |
---|
5625 | long int strto( const char * sptr, char ** eptr, int base ); |
---|
5626 | unsigned long int strto( const char * sptr, char ** eptr, int base ); |
---|
5627 | long long int strto( const char * sptr, char ** eptr, int base ); |
---|
5628 | unsigned long long int strto( const char * sptr, char ** eptr, int base ); |
---|
5629 | float strto( const char * sptr, char ** eptr ); |
---|
5630 | double strto( const char * sptr, char ** eptr ); |
---|
5631 | long double strto( const char * sptr, char ** eptr ); |
---|
5632 | float _Complex strto( const char * sptr, char ** eptr ); |
---|
5633 | double _Complex strto( const char * sptr, char ** eptr ); |
---|
5634 | long double _Complex strto( const char * sptr, char ** eptr ); |
---|
5635 | \end{cfa} |
---|
5636 | |
---|
5637 | |
---|
5638 | \subsection{Search / Sort} |
---|
5639 | |
---|
5640 | \leavevmode |
---|
5641 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5642 | forall( otype T | { int ?<?( T, T ); } ) §\C{// location}§ |
---|
5643 | T * bsearch( T key, const T * arr, size_t dim );§\indexc{bsearch}§ |
---|
5644 | |
---|
5645 | forall( otype T | { int ?<?( T, T ); } ) §\C{// position}§ |
---|
5646 | unsigned int bsearch( T key, const T * arr, size_t dim ); |
---|
5647 | |
---|
5648 | forall( otype T | { int ?<?( T, T ); } ) |
---|
5649 | void qsort( const T * arr, size_t dim );§\indexc{qsort}§ |
---|
5650 | \end{cfa} |
---|
5651 | |
---|
5652 | |
---|
5653 | \subsection{Absolute Value} |
---|
5654 | |
---|
5655 | \leavevmode |
---|
5656 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5657 | unsigned char abs( signed char );§\indexc{abs}§ |
---|
5658 | int abs( int ); |
---|
5659 | unsigned long int abs( long int ); |
---|
5660 | unsigned long long int abs( long long int ); |
---|
5661 | float abs( float ); |
---|
5662 | double abs( double ); |
---|
5663 | long double abs( long double ); |
---|
5664 | float abs( float _Complex ); |
---|
5665 | double abs( double _Complex ); |
---|
5666 | long double abs( long double _Complex ); |
---|
5667 | forall( otype T | { void ?{}( T *, zero_t ); int ?<?( T, T ); T -?( T ); } ) |
---|
5668 | T abs( T ); |
---|
5669 | \end{cfa} |
---|
5670 | |
---|
5671 | |
---|
5672 | \subsection{Random Numbers} |
---|
5673 | |
---|
5674 | \leavevmode |
---|
5675 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5676 | void rand48seed( long int s );§\indexc{rand48seed}§ |
---|
5677 | char rand48();§\indexc{rand48}§ |
---|
5678 | int rand48(); |
---|
5679 | unsigned int rand48(); |
---|
5680 | long int rand48(); |
---|
5681 | unsigned long int rand48(); |
---|
5682 | float rand48(); |
---|
5683 | double rand48(); |
---|
5684 | float _Complex rand48(); |
---|
5685 | double _Complex rand48(); |
---|
5686 | long double _Complex rand48(); |
---|
5687 | \end{cfa} |
---|
5688 | |
---|
5689 | |
---|
5690 | \subsection{Algorithms} |
---|
5691 | |
---|
5692 | \leavevmode |
---|
5693 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5694 | forall( otype T | { int ?<?( T, T ); } ) T min( T t1, T t2 );§\indexc{min}§ |
---|
5695 | forall( otype T | { int ?>?( T, T ); } ) T max( T t1, T t2 );§\indexc{max}§ |
---|
5696 | forall( otype T | { T min( T, T ); T max( T, T ); } ) T clamp( T value, T min_val, T max_val );§\indexc{clamp}§ |
---|
5697 | forall( otype T ) void swap( T * t1, T * t2 );§\indexc{swap}§ |
---|
5698 | \end{cfa} |
---|
5699 | |
---|
5700 | |
---|
5701 | \section{Math Library} |
---|
5702 | \label{s:Math Library} |
---|
5703 | |
---|
5704 | The \CFA math-library wraps explicitly-polymorphic C math-routines into implicitly-polymorphic versions. |
---|
5705 | |
---|
5706 | |
---|
5707 | \subsection{General} |
---|
5708 | |
---|
5709 | \leavevmode |
---|
5710 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5711 | float ?%?( float, float );§\indexc{fmod}§ |
---|
5712 | float fmod( float, float ); |
---|
5713 | double ?%?( double, double ); |
---|
5714 | double fmod( double, double ); |
---|
5715 | long double ?%?( long double, long double ); |
---|
5716 | long double fmod( long double, long double ); |
---|
5717 | |
---|
5718 | float remainder( float, float );§\indexc{remainder}§ |
---|
5719 | double remainder( double, double ); |
---|
5720 | long double remainder( long double, long double ); |
---|
5721 | |
---|
5722 | [ int, float ] remquo( float, float );§\indexc{remquo}§ |
---|
5723 | float remquo( float, float, int * ); |
---|
5724 | [ int, double ] remquo( double, double ); |
---|
5725 | double remquo( double, double, int * ); |
---|
5726 | [ int, long double ] remquo( long double, long double ); |
---|
5727 | long double remquo( long double, long double, int * ); |
---|
5728 | |
---|
5729 | [ int, float ] div( float, float ); // alternative name for remquo |
---|
5730 | float div( float, float, int * );§\indexc{div}§ |
---|
5731 | [ int, double ] div( double, double ); |
---|
5732 | double div( double, double, int * ); |
---|
5733 | [ int, long double ] div( long double, long double ); |
---|
5734 | long double div( long double, long double, int * ); |
---|
5735 | |
---|
5736 | float fma( float, float, float );§\indexc{fma}§ |
---|
5737 | double fma( double, double, double ); |
---|
5738 | long double fma( long double, long double, long double ); |
---|
5739 | |
---|
5740 | float fdim( float, float );§\indexc{fdim}§ |
---|
5741 | double fdim( double, double ); |
---|
5742 | long double fdim( long double, long double ); |
---|
5743 | |
---|
5744 | float nan( const char * );§\indexc{nan}§ |
---|
5745 | double nan( const char * ); |
---|
5746 | long double nan( const char * ); |
---|
5747 | \end{cfa} |
---|
5748 | |
---|
5749 | |
---|
5750 | \subsection{Exponential} |
---|
5751 | |
---|
5752 | \leavevmode |
---|
5753 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5754 | float exp( float );§\indexc{exp}§ |
---|
5755 | double exp( double ); |
---|
5756 | long double exp( long double ); |
---|
5757 | float _Complex exp( float _Complex ); |
---|
5758 | double _Complex exp( double _Complex ); |
---|
5759 | long double _Complex exp( long double _Complex ); |
---|
5760 | |
---|
5761 | float exp2( float );§\indexc{exp2}§ |
---|
5762 | double exp2( double ); |
---|
5763 | long double exp2( long double ); |
---|
5764 | float _Complex exp2( float _Complex ); |
---|
5765 | double _Complex exp2( double _Complex ); |
---|
5766 | long double _Complex exp2( long double _Complex ); |
---|
5767 | |
---|
5768 | float expm1( float );§\indexc{expm1}§ |
---|
5769 | double expm1( double ); |
---|
5770 | long double expm1( long double ); |
---|
5771 | |
---|
5772 | float log( float );§\indexc{log}§ |
---|
5773 | double log( double ); |
---|
5774 | long double log( long double ); |
---|
5775 | float _Complex log( float _Complex ); |
---|
5776 | double _Complex log( double _Complex ); |
---|
5777 | long double _Complex log( long double _Complex ); |
---|
5778 | |
---|
5779 | float log2( float );§\indexc{log2}§ |
---|
5780 | double log2( double ); |
---|
5781 | long double log2( long double ); |
---|
5782 | float _Complex log2( float _Complex ); |
---|
5783 | double _Complex log2( double _Complex ); |
---|
5784 | long double _Complex log2( long double _Complex ); |
---|
5785 | |
---|
5786 | float log10( float );§\indexc{log10}§ |
---|
5787 | double log10( double ); |
---|
5788 | long double log10( long double ); |
---|
5789 | float _Complex log10( float _Complex ); |
---|
5790 | double _Complex log10( double _Complex ); |
---|
5791 | long double _Complex log10( long double _Complex ); |
---|
5792 | |
---|
5793 | float log1p( float );§\indexc{log1p}§ |
---|
5794 | double log1p( double ); |
---|
5795 | long double log1p( long double ); |
---|
5796 | |
---|
5797 | int ilogb( float );§\indexc{ilogb}§ |
---|
5798 | int ilogb( double ); |
---|
5799 | int ilogb( long double ); |
---|
5800 | |
---|
5801 | float logb( float );§\indexc{logb}§ |
---|
5802 | double logb( double ); |
---|
5803 | long double logb( long double ); |
---|
5804 | \end{cfa} |
---|
5805 | |
---|
5806 | |
---|
5807 | \subsection{Power} |
---|
5808 | |
---|
5809 | \leavevmode |
---|
5810 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5811 | float sqrt( float );§\indexc{sqrt}§ |
---|
5812 | double sqrt( double ); |
---|
5813 | long double sqrt( long double ); |
---|
5814 | float _Complex sqrt( float _Complex ); |
---|
5815 | double _Complex sqrt( double _Complex ); |
---|
5816 | long double _Complex sqrt( long double _Complex ); |
---|
5817 | |
---|
5818 | float cbrt( float );§\indexc{cbrt}§ |
---|
5819 | double cbrt( double ); |
---|
5820 | long double cbrt( long double ); |
---|
5821 | |
---|
5822 | float hypot( float, float );§\indexc{hypot}§ |
---|
5823 | double hypot( double, double ); |
---|
5824 | long double hypot( long double, long double ); |
---|
5825 | |
---|
5826 | float pow( float, float );§\indexc{pow}§ |
---|
5827 | double pow( double, double ); |
---|
5828 | long double pow( long double, long double ); |
---|
5829 | float _Complex pow( float _Complex, float _Complex ); |
---|
5830 | double _Complex pow( double _Complex, double _Complex ); |
---|
5831 | long double _Complex pow( long double _Complex, long double _Complex ); |
---|
5832 | \end{cfa} |
---|
5833 | |
---|
5834 | |
---|
5835 | \subsection{Trigonometric} |
---|
5836 | |
---|
5837 | \leavevmode |
---|
5838 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5839 | float sin( float );§\indexc{sin}§ |
---|
5840 | double sin( double ); |
---|
5841 | long double sin( long double ); |
---|
5842 | float _Complex sin( float _Complex ); |
---|
5843 | double _Complex sin( double _Complex ); |
---|
5844 | long double _Complex sin( long double _Complex ); |
---|
5845 | |
---|
5846 | float cos( float );§\indexc{cos}§ |
---|
5847 | double cos( double ); |
---|
5848 | long double cos( long double ); |
---|
5849 | float _Complex cos( float _Complex ); |
---|
5850 | double _Complex cos( double _Complex ); |
---|
5851 | long double _Complex cos( long double _Complex ); |
---|
5852 | |
---|
5853 | float tan( float );§\indexc{tan}§ |
---|
5854 | double tan( double ); |
---|
5855 | long double tan( long double ); |
---|
5856 | float _Complex tan( float _Complex ); |
---|
5857 | double _Complex tan( double _Complex ); |
---|
5858 | long double _Complex tan( long double _Complex ); |
---|
5859 | |
---|
5860 | float asin( float );§\indexc{asin}§ |
---|
5861 | double asin( double ); |
---|
5862 | long double asin( long double ); |
---|
5863 | float _Complex asin( float _Complex ); |
---|
5864 | double _Complex asin( double _Complex ); |
---|
5865 | long double _Complex asin( long double _Complex ); |
---|
5866 | |
---|
5867 | float acos( float );§\indexc{acos}§ |
---|
5868 | double acos( double ); |
---|
5869 | long double acos( long double ); |
---|
5870 | float _Complex acos( float _Complex ); |
---|
5871 | double _Complex acos( double _Complex ); |
---|
5872 | long double _Complex acos( long double _Complex ); |
---|
5873 | |
---|
5874 | float atan( float );§\indexc{atan}§ |
---|
5875 | double atan( double ); |
---|
5876 | long double atan( long double ); |
---|
5877 | float _Complex atan( float _Complex ); |
---|
5878 | double _Complex atan( double _Complex ); |
---|
5879 | long double _Complex atan( long double _Complex ); |
---|
5880 | |
---|
5881 | float atan2( float, float );§\indexc{atan2}§ |
---|
5882 | double atan2( double, double ); |
---|
5883 | long double atan2( long double, long double ); |
---|
5884 | |
---|
5885 | float atan( float, float ); // alternative name for atan2 |
---|
5886 | double atan( double, double );§\indexc{atan}§ |
---|
5887 | long double atan( long double, long double ); |
---|
5888 | \end{cfa} |
---|
5889 | |
---|
5890 | |
---|
5891 | \subsection{Hyperbolic} |
---|
5892 | |
---|
5893 | \leavevmode |
---|
5894 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5895 | float sinh( float );§\indexc{sinh}§ |
---|
5896 | double sinh( double ); |
---|
5897 | long double sinh( long double ); |
---|
5898 | float _Complex sinh( float _Complex ); |
---|
5899 | double _Complex sinh( double _Complex ); |
---|
5900 | long double _Complex sinh( long double _Complex ); |
---|
5901 | |
---|
5902 | float cosh( float );§\indexc{cosh}§ |
---|
5903 | double cosh( double ); |
---|
5904 | long double cosh( long double ); |
---|
5905 | float _Complex cosh( float _Complex ); |
---|
5906 | double _Complex cosh( double _Complex ); |
---|
5907 | long double _Complex cosh( long double _Complex ); |
---|
5908 | |
---|
5909 | float tanh( float );§\indexc{tanh}§ |
---|
5910 | double tanh( double ); |
---|
5911 | long double tanh( long double ); |
---|
5912 | float _Complex tanh( float _Complex ); |
---|
5913 | double _Complex tanh( double _Complex ); |
---|
5914 | long double _Complex tanh( long double _Complex ); |
---|
5915 | |
---|
5916 | float asinh( float );§\indexc{asinh}§ |
---|
5917 | double asinh( double ); |
---|
5918 | long double asinh( long double ); |
---|
5919 | float _Complex asinh( float _Complex ); |
---|
5920 | double _Complex asinh( double _Complex ); |
---|
5921 | long double _Complex asinh( long double _Complex ); |
---|
5922 | |
---|
5923 | float acosh( float );§\indexc{acosh}§ |
---|
5924 | double acosh( double ); |
---|
5925 | long double acosh( long double ); |
---|
5926 | float _Complex acosh( float _Complex ); |
---|
5927 | double _Complex acosh( double _Complex ); |
---|
5928 | long double _Complex acosh( long double _Complex ); |
---|
5929 | |
---|
5930 | float atanh( float );§\indexc{atanh}§ |
---|
5931 | double atanh( double ); |
---|
5932 | long double atanh( long double ); |
---|
5933 | float _Complex atanh( float _Complex ); |
---|
5934 | double _Complex atanh( double _Complex ); |
---|
5935 | long double _Complex atanh( long double _Complex ); |
---|
5936 | \end{cfa} |
---|
5937 | |
---|
5938 | |
---|
5939 | \subsection{Error / Gamma} |
---|
5940 | |
---|
5941 | \leavevmode |
---|
5942 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5943 | float erf( float );§\indexc{erf}§ |
---|
5944 | double erf( double ); |
---|
5945 | long double erf( long double ); |
---|
5946 | float _Complex erf( float _Complex ); |
---|
5947 | double _Complex erf( double _Complex ); |
---|
5948 | long double _Complex erf( long double _Complex ); |
---|
5949 | |
---|
5950 | float erfc( float );§\indexc{erfc}§ |
---|
5951 | double erfc( double ); |
---|
5952 | long double erfc( long double ); |
---|
5953 | float _Complex erfc( float _Complex ); |
---|
5954 | double _Complex erfc( double _Complex ); |
---|
5955 | long double _Complex erfc( long double _Complex ); |
---|
5956 | |
---|
5957 | float lgamma( float );§\indexc{lgamma}§ |
---|
5958 | double lgamma( double ); |
---|
5959 | long double lgamma( long double ); |
---|
5960 | float lgamma( float, int * ); |
---|
5961 | double lgamma( double, int * ); |
---|
5962 | long double lgamma( long double, int * ); |
---|
5963 | |
---|
5964 | float tgamma( float );§\indexc{tgamma}§ |
---|
5965 | double tgamma( double ); |
---|
5966 | long double tgamma( long double ); |
---|
5967 | \end{cfa} |
---|
5968 | |
---|
5969 | |
---|
5970 | \subsection{Nearest Integer} |
---|
5971 | |
---|
5972 | \leavevmode |
---|
5973 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5974 | float floor( float );§\indexc{floor}§ |
---|
5975 | double floor( double ); |
---|
5976 | long double floor( long double ); |
---|
5977 | |
---|
5978 | float ceil( float );§\indexc{ceil}§ |
---|
5979 | double ceil( double ); |
---|
5980 | long double ceil( long double ); |
---|
5981 | |
---|
5982 | float trunc( float );§\indexc{trunc}§ |
---|
5983 | double trunc( double ); |
---|
5984 | long double trunc( long double ); |
---|
5985 | |
---|
5986 | float rint( float );§\indexc{rint}§ |
---|
5987 | long double rint( long double ); |
---|
5988 | long int rint( float ); |
---|
5989 | long int rint( double ); |
---|
5990 | long int rint( long double ); |
---|
5991 | long long int rint( float ); |
---|
5992 | long long int rint( double ); |
---|
5993 | long long int rint( long double ); |
---|
5994 | |
---|
5995 | long int lrint( float );§\indexc{lrint}§ |
---|
5996 | long int lrint( double ); |
---|
5997 | long int lrint( long double ); |
---|
5998 | long long int llrint( float ); |
---|
5999 | long long int llrint( double ); |
---|
6000 | long long int llrint( long double ); |
---|
6001 | |
---|
6002 | float nearbyint( float );§\indexc{nearbyint}§ |
---|
6003 | double nearbyint( double ); |
---|
6004 | long double nearbyint( long double ); |
---|
6005 | |
---|
6006 | float round( float );§\indexc{round}§ |
---|
6007 | long double round( long double ); |
---|
6008 | long int round( float ); |
---|
6009 | long int round( double ); |
---|
6010 | long int round( long double ); |
---|
6011 | long long int round( float ); |
---|
6012 | long long int round( double ); |
---|
6013 | long long int round( long double ); |
---|
6014 | |
---|
6015 | long int lround( float );§\indexc{lround}§ |
---|
6016 | long int lround( double ); |
---|
6017 | long int lround( long double ); |
---|
6018 | long long int llround( float ); |
---|
6019 | long long int llround( double ); |
---|
6020 | long long int llround( long double ); |
---|
6021 | \end{cfa} |
---|
6022 | |
---|
6023 | |
---|
6024 | \subsection{Manipulation} |
---|
6025 | |
---|
6026 | \leavevmode |
---|
6027 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
6028 | float copysign( float, float );§\indexc{copysign}§ |
---|
6029 | double copysign( double, double ); |
---|
6030 | long double copysign( long double, long double ); |
---|
6031 | |
---|
6032 | float frexp( float, int * );§\indexc{frexp}§ |
---|
6033 | double frexp( double, int * ); |
---|
6034 | long double frexp( long double, int * ); |
---|
6035 | |
---|
6036 | float ldexp( float, int );§\indexc{ldexp}§ |
---|
6037 | double ldexp( double, int ); |
---|
6038 | long double ldexp( long double, int ); |
---|
6039 | |
---|
6040 | [ float, float ] modf( float );§\indexc{modf}§ |
---|
6041 | float modf( float, float * ); |
---|
6042 | [ double, double ] modf( double ); |
---|
6043 | double modf( double, double * ); |
---|
6044 | [ long double, long double ] modf( long double ); |
---|
6045 | long double modf( long double, long double * ); |
---|
6046 | |
---|
6047 | float nextafter( float, float );§\indexc{nextafter}§ |
---|
6048 | double nextafter( double, double ); |
---|
6049 | long double nextafter( long double, long double ); |
---|
6050 | |
---|
6051 | float nexttoward( float, long double );§\indexc{nexttoward}§ |
---|
6052 | double nexttoward( double, long double ); |
---|
6053 | long double nexttoward( long double, long double ); |
---|
6054 | |
---|
6055 | float scalbn( float, int );§\indexc{scalbn}§ |
---|
6056 | double scalbn( double, int ); |
---|
6057 | long double scalbn( long double, int ); |
---|
6058 | |
---|
6059 | float scalbln( float, long int );§\indexc{scalbln}§ |
---|
6060 | double scalbln( double, long int ); |
---|
6061 | long double scalbln( long double, long int ); |
---|
6062 | \end{cfa} |
---|
6063 | |
---|
6064 | |
---|
6065 | \section{Multi-precision Integers} |
---|
6066 | \label{s:MultiPrecisionIntegers} |
---|
6067 | |
---|
6068 | \CFA has an interface to the GMP \Index{multi-precision} signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP. |
---|
6069 | The \CFA interface wraps GMP routines into operator routines to make programming with multi-precision integers identical to using fixed-sized integers. |
---|
6070 | The \CFA type name for multi-precision signed-integers is \Indexc{Int} and the header file is \Indexc{gmp}. |
---|
6071 | |
---|
6072 | \begin{cfa} |
---|
6073 | void ?{}( Int * this ); §\C{// constructor}§ |
---|
6074 | void ?{}( Int * this, Int init ); |
---|
6075 | void ?{}( Int * this, zero_t ); |
---|
6076 | void ?{}( Int * this, one_t ); |
---|
6077 | void ?{}( Int * this, signed long int init ); |
---|
6078 | void ?{}( Int * this, unsigned long int init ); |
---|
6079 | void ?{}( Int * this, const char * val ); |
---|
6080 | void ^?{}( Int * this ); |
---|
6081 | |
---|
6082 | Int ?=?( Int * lhs, Int rhs ); §\C{// assignment}§ |
---|
6083 | Int ?=?( Int * lhs, long int rhs ); |
---|
6084 | Int ?=?( Int * lhs, unsigned long int rhs ); |
---|
6085 | Int ?=?( Int * lhs, const char * rhs ); |
---|
6086 | |
---|
6087 | char ?=?( char * lhs, Int rhs ); |
---|
6088 | short int ?=?( short int * lhs, Int rhs ); |
---|
6089 | int ?=?( int * lhs, Int rhs ); |
---|
6090 | long int ?=?( long int * lhs, Int rhs ); |
---|
6091 | unsigned char ?=?( unsigned char * lhs, Int rhs ); |
---|
6092 | unsigned short int ?=?( unsigned short int * lhs, Int rhs ); |
---|
6093 | unsigned int ?=?( unsigned int * lhs, Int rhs ); |
---|
6094 | unsigned long int ?=?( unsigned long int * lhs, Int rhs ); |
---|
6095 | |
---|
6096 | long int narrow( Int val ); |
---|
6097 | unsigned long int narrow( Int val ); |
---|
6098 | |
---|
6099 | int ?==?( Int oper1, Int oper2 ); §\C{// comparison}§ |
---|
6100 | int ?==?( Int oper1, long int oper2 ); |
---|
6101 | int ?==?( long int oper2, Int oper1 ); |
---|
6102 | int ?==?( Int oper1, unsigned long int oper2 ); |
---|
6103 | int ?==?( unsigned long int oper2, Int oper1 ); |
---|
6104 | |
---|
6105 | int ?!=?( Int oper1, Int oper2 ); |
---|
6106 | int ?!=?( Int oper1, long int oper2 ); |
---|
6107 | int ?!=?( long int oper1, Int oper2 ); |
---|
6108 | int ?!=?( Int oper1, unsigned long int oper2 ); |
---|
6109 | int ?!=?( unsigned long int oper1, Int oper2 ); |
---|
6110 | |
---|
6111 | int ?<?( Int oper1, Int oper2 ); |
---|
6112 | int ?<?( Int oper1, long int oper2 ); |
---|
6113 | int ?<?( long int oper2, Int oper1 ); |
---|
6114 | int ?<?( Int oper1, unsigned long int oper2 ); |
---|
6115 | int ?<?( unsigned long int oper2, Int oper1 ); |
---|
6116 | |
---|
6117 | int ?<=?( Int oper1, Int oper2 ); |
---|
6118 | int ?<=?( Int oper1, long int oper2 ); |
---|
6119 | int ?<=?( long int oper2, Int oper1 ); |
---|
6120 | int ?<=?( Int oper1, unsigned long int oper2 ); |
---|
6121 | int ?<=?( unsigned long int oper2, Int oper1 ); |
---|
6122 | |
---|
6123 | int ?>?( Int oper1, Int oper2 ); |
---|
6124 | int ?>?( Int oper1, long int oper2 ); |
---|
6125 | int ?>?( long int oper1, Int oper2 ); |
---|
6126 | int ?>?( Int oper1, unsigned long int oper2 ); |
---|
6127 | int ?>?( unsigned long int oper1, Int oper2 ); |
---|
6128 | |
---|
6129 | int ?>=?( Int oper1, Int oper2 ); |
---|
6130 | int ?>=?( Int oper1, long int oper2 ); |
---|
6131 | int ?>=?( long int oper1, Int oper2 ); |
---|
6132 | int ?>=?( Int oper1, unsigned long int oper2 ); |
---|
6133 | int ?>=?( unsigned long int oper1, Int oper2 ); |
---|
6134 | |
---|
6135 | Int +?( Int oper ); §\C{// arithmetic}§ |
---|
6136 | Int -?( Int oper ); |
---|
6137 | Int ~?( Int oper ); |
---|
6138 | |
---|
6139 | Int ?&?( Int oper1, Int oper2 ); |
---|
6140 | Int ?&?( Int oper1, long int oper2 ); |
---|
6141 | Int ?&?( long int oper1, Int oper2 ); |
---|
6142 | Int ?&?( Int oper1, unsigned long int oper2 ); |
---|
6143 | Int ?&?( unsigned long int oper1, Int oper2 ); |
---|
6144 | Int ?&=?( Int * lhs, Int rhs ); |
---|
6145 | |
---|
6146 | Int ?|?( Int oper1, Int oper2 ); |
---|
6147 | Int ?|?( Int oper1, long int oper2 ); |
---|
6148 | Int ?|?( long int oper1, Int oper2 ); |
---|
6149 | Int ?|?( Int oper1, unsigned long int oper2 ); |
---|
6150 | Int ?|?( unsigned long int oper1, Int oper2 ); |
---|
6151 | Int ?|=?( Int * lhs, Int rhs ); |
---|
6152 | |
---|
6153 | Int ?^?( Int oper1, Int oper2 ); |
---|
6154 | Int ?^?( Int oper1, long int oper2 ); |
---|
6155 | Int ?^?( long int oper1, Int oper2 ); |
---|
6156 | Int ?^?( Int oper1, unsigned long int oper2 ); |
---|
6157 | Int ?^?( unsigned long int oper1, Int oper2 ); |
---|
6158 | Int ?^=?( Int * lhs, Int rhs ); |
---|
6159 | |
---|
6160 | Int ?+?( Int addend1, Int addend2 ); |
---|
6161 | Int ?+?( Int addend1, long int addend2 ); |
---|
6162 | Int ?+?( long int addend2, Int addend1 ); |
---|
6163 | Int ?+?( Int addend1, unsigned long int addend2 ); |
---|
6164 | Int ?+?( unsigned long int addend2, Int addend1 ); |
---|
6165 | Int ?+=?( Int * lhs, Int rhs ); |
---|
6166 | Int ?+=?( Int * lhs, long int rhs ); |
---|
6167 | Int ?+=?( Int * lhs, unsigned long int rhs ); |
---|
6168 | Int ++?( Int * lhs ); |
---|
6169 | Int ?++( Int * lhs ); |
---|
6170 | |
---|
6171 | Int ?-?( Int minuend, Int subtrahend ); |
---|
6172 | Int ?-?( Int minuend, long int subtrahend ); |
---|
6173 | Int ?-?( long int minuend, Int subtrahend ); |
---|
6174 | Int ?-?( Int minuend, unsigned long int subtrahend ); |
---|
6175 | Int ?-?( unsigned long int minuend, Int subtrahend ); |
---|
6176 | Int ?-=?( Int * lhs, Int rhs ); |
---|
6177 | Int ?-=?( Int * lhs, long int rhs ); |
---|
6178 | Int ?-=?( Int * lhs, unsigned long int rhs ); |
---|
6179 | Int --?( Int * lhs ); |
---|
6180 | Int ?--( Int * lhs ); |
---|
6181 | |
---|
6182 | Int ?*?( Int multiplicator, Int multiplicand ); |
---|
6183 | Int ?*?( Int multiplicator, long int multiplicand ); |
---|
6184 | Int ?*?( long int multiplicand, Int multiplicator ); |
---|
6185 | Int ?*?( Int multiplicator, unsigned long int multiplicand ); |
---|
6186 | Int ?*?( unsigned long int multiplicand, Int multiplicator ); |
---|
6187 | Int ?*=?( Int * lhs, Int rhs ); |
---|
6188 | Int ?*=?( Int * lhs, long int rhs ); |
---|
6189 | Int ?*=?( Int * lhs, unsigned long int rhs ); |
---|
6190 | |
---|
6191 | Int ?/?( Int dividend, Int divisor ); |
---|
6192 | Int ?/?( Int dividend, unsigned long int divisor ); |
---|
6193 | Int ?/?( unsigned long int dividend, Int divisor ); |
---|
6194 | Int ?/?( Int dividend, long int divisor ); |
---|
6195 | Int ?/?( long int dividend, Int divisor ); |
---|
6196 | Int ?/=?( Int * lhs, Int rhs ); |
---|
6197 | Int ?/=?( Int * lhs, long int rhs ); |
---|
6198 | Int ?/=?( Int * lhs, unsigned long int rhs ); |
---|
6199 | |
---|
6200 | [ Int, Int ] div( Int dividend, Int divisor ); |
---|
6201 | [ Int, Int ] div( Int dividend, unsigned long int divisor ); |
---|
6202 | |
---|
6203 | Int ?%?( Int dividend, Int divisor ); |
---|
6204 | Int ?%?( Int dividend, unsigned long int divisor ); |
---|
6205 | Int ?%?( unsigned long int dividend, Int divisor ); |
---|
6206 | Int ?%?( Int dividend, long int divisor ); |
---|
6207 | Int ?%?( long int dividend, Int divisor ); |
---|
6208 | Int ?%=?( Int * lhs, Int rhs ); |
---|
6209 | Int ?%=?( Int * lhs, long int rhs ); |
---|
6210 | Int ?%=?( Int * lhs, unsigned long int rhs ); |
---|
6211 | |
---|
6212 | Int ?<<?( Int shiften, mp_bitcnt_t shift ); |
---|
6213 | Int ?<<=?( Int * lhs, mp_bitcnt_t shift ); |
---|
6214 | Int ?>>?( Int shiften, mp_bitcnt_t shift ); |
---|
6215 | Int ?>>=?( Int * lhs, mp_bitcnt_t shift ); |
---|
6216 | |
---|
6217 | Int abs( Int oper ); §\C{// number functions}§ |
---|
6218 | Int fact( unsigned long int N ); |
---|
6219 | Int gcd( Int oper1, Int oper2 ); |
---|
6220 | Int pow( Int base, unsigned long int exponent ); |
---|
6221 | Int pow( unsigned long int base, unsigned long int exponent ); |
---|
6222 | void srandom( gmp_randstate_t state ); |
---|
6223 | Int random( gmp_randstate_t state, mp_bitcnt_t n ); |
---|
6224 | Int random( gmp_randstate_t state, Int n ); |
---|
6225 | Int random( gmp_randstate_t state, mp_size_t max_size ); |
---|
6226 | int sgn( Int oper ); |
---|
6227 | Int sqrt( Int oper ); |
---|
6228 | |
---|
6229 | forall( dtype istype | istream( istype ) ) istype * ?|?( istype * is, Int * mp ); §\C{// I/O}§ |
---|
6230 | forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype * os, Int mp ); |
---|
6231 | \end{cfa} |
---|
6232 | |
---|
6233 | The following factorial programs contrast using GMP with the \CFA and C interfaces, where the output from these programs appears in \VRef[Figure]{f:MultiPrecisionFactorials}. |
---|
6234 | (Compile with flag \Indexc{-lgmp} to link with the GMP library.) |
---|
6235 | \begin{quote2} |
---|
6236 | \begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}} |
---|
6237 | \multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}} \\ |
---|
6238 | \hline |
---|
6239 | \begin{cfa} |
---|
6240 | #include <gmp>§\indexc{gmp}§ |
---|
6241 | int main( void ) { |
---|
6242 | sout | "Factorial Numbers" | endl; |
---|
6243 | Int fact = 1; |
---|
6244 | |
---|
6245 | sout | 0 | fact | endl; |
---|
6246 | for ( unsigned int i = 1; i <= 40; i += 1 ) { |
---|
6247 | fact *= i; |
---|
6248 | sout | i | fact | endl; |
---|
6249 | } |
---|
6250 | } |
---|
6251 | \end{cfa} |
---|
6252 | & |
---|
6253 | \begin{cfa} |
---|
6254 | #include <gmp.h>§\indexc{gmp.h}§ |
---|
6255 | int main( void ) { |
---|
6256 | ®gmp_printf®( "Factorial Numbers\n" ); |
---|
6257 | ®mpz_t® fact; |
---|
6258 | ®mpz_init_set_ui®( fact, 1 ); |
---|
6259 | ®gmp_printf®( "%d %Zd\n", 0, fact ); |
---|
6260 | for ( unsigned int i = 1; i <= 40; i += 1 ) { |
---|
6261 | ®mpz_mul_ui®( fact, fact, i ); |
---|
6262 | ®gmp_printf®( "%d %Zd\n", i, fact ); |
---|
6263 | } |
---|
6264 | } |
---|
6265 | \end{cfa} |
---|
6266 | \end{tabular} |
---|
6267 | \end{quote2} |
---|
6268 | |
---|
6269 | \begin{figure} |
---|
6270 | \begin{cfa} |
---|
6271 | Factorial Numbers |
---|
6272 | 0 1 |
---|
6273 | 1 1 |
---|
6274 | 2 2 |
---|
6275 | 3 6 |
---|
6276 | 4 24 |
---|
6277 | 5 120 |
---|
6278 | 6 720 |
---|
6279 | 7 5040 |
---|
6280 | 8 40320 |
---|
6281 | 9 362880 |
---|
6282 | 10 3628800 |
---|
6283 | 11 39916800 |
---|
6284 | 12 479001600 |
---|
6285 | 13 6227020800 |
---|
6286 | 14 87178291200 |
---|
6287 | 15 1307674368000 |
---|
6288 | 16 20922789888000 |
---|
6289 | 17 355687428096000 |
---|
6290 | 18 6402373705728000 |
---|
6291 | 19 121645100408832000 |
---|
6292 | 20 2432902008176640000 |
---|
6293 | 21 51090942171709440000 |
---|
6294 | 22 1124000727777607680000 |
---|
6295 | 23 25852016738884976640000 |
---|
6296 | 24 620448401733239439360000 |
---|
6297 | 25 15511210043330985984000000 |
---|
6298 | 26 403291461126605635584000000 |
---|
6299 | 27 10888869450418352160768000000 |
---|
6300 | 28 304888344611713860501504000000 |
---|
6301 | 29 8841761993739701954543616000000 |
---|
6302 | 30 265252859812191058636308480000000 |
---|
6303 | 31 8222838654177922817725562880000000 |
---|
6304 | 32 263130836933693530167218012160000000 |
---|
6305 | 33 8683317618811886495518194401280000000 |
---|
6306 | 34 295232799039604140847618609643520000000 |
---|
6307 | 35 10333147966386144929666651337523200000000 |
---|
6308 | 36 371993326789901217467999448150835200000000 |
---|
6309 | 37 13763753091226345046315979581580902400000000 |
---|
6310 | 38 523022617466601111760007224100074291200000000 |
---|
6311 | 39 20397882081197443358640281739902897356800000000 |
---|
6312 | 40 815915283247897734345611269596115894272000000000 |
---|
6313 | \end{cfa} |
---|
6314 | \caption{Multi-precision Factorials} |
---|
6315 | \label{f:MultiPrecisionFactorials} |
---|
6316 | \end{figure} |
---|
6317 | |
---|
6318 | |
---|
6319 | \section{Rational Numbers} |
---|
6320 | \label{s:RationalNumbers} |
---|
6321 | |
---|
6322 | Rational numbers are numbers written as a ratio, \ie as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers. |
---|
6323 | When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible. |
---|
6324 | |
---|
6325 | \begin{cfa}[belowskip=0pt] |
---|
6326 | // implementation |
---|
6327 | struct Rational {§\indexc{Rational}§ |
---|
6328 | long int numerator, denominator; // invariant: denominator > 0 |
---|
6329 | }; // Rational |
---|
6330 | |
---|
6331 | Rational rational(); §\C{// constructors}§ |
---|
6332 | Rational rational( long int n ); |
---|
6333 | Rational rational( long int n, long int d ); |
---|
6334 | void ?{}( Rational * r, zero_t ); |
---|
6335 | void ?{}( Rational * r, one_t ); |
---|
6336 | |
---|
6337 | long int numerator( Rational r ); §\C{// numerator/denominator getter/setter}§ |
---|
6338 | long int numerator( Rational r, long int n ); |
---|
6339 | long int denominator( Rational r ); |
---|
6340 | long int denominator( Rational r, long int d ); |
---|
6341 | |
---|
6342 | int ?==?( Rational l, Rational r ); §\C{// comparison}§ |
---|
6343 | int ?!=?( Rational l, Rational r ); |
---|
6344 | int ?<?( Rational l, Rational r ); |
---|
6345 | int ?<=?( Rational l, Rational r ); |
---|
6346 | int ?>?( Rational l, Rational r ); |
---|
6347 | int ?>=?( Rational l, Rational r ); |
---|
6348 | |
---|
6349 | Rational -?( Rational r ); §\C{// arithmetic}§ |
---|
6350 | Rational ?+?( Rational l, Rational r ); |
---|
6351 | Rational ?-?( Rational l, Rational r ); |
---|
6352 | Rational ?*?( Rational l, Rational r ); |
---|
6353 | Rational ?/?( Rational l, Rational r ); |
---|
6354 | |
---|
6355 | double widen( Rational r ); §\C{// conversion}§ |
---|
6356 | Rational narrow( double f, long int md ); |
---|
6357 | |
---|
6358 | forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * ); // I/O |
---|
6359 | forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational ); |
---|
6360 | \end{cfa} |
---|
6361 | |
---|
6362 | |
---|
6363 | \bibliographystyle{plain} |
---|
6364 | \bibliography{cfa} |
---|
6365 | |
---|
6366 | |
---|
6367 | \addcontentsline{toc}{section}{\indexname} % add index name to table of contents |
---|
6368 | \begin{theindex} |
---|
6369 | Italic page numbers give the location of the main entry for the referenced term. |
---|
6370 | Plain page numbers denote uses of the indexed term. |
---|
6371 | Entries for grammar non-terminals are italicized. |
---|
6372 | A typewriter font is used for grammar terminals and program identifiers. |
---|
6373 | \indexspace |
---|
6374 | \input{user.ind} |
---|
6375 | \end{theindex} |
---|
6376 | |
---|
6377 | |
---|
6378 | \end{document} |
---|
6379 | |
---|
6380 | % Local Variables: % |
---|
6381 | % tab-width: 4 % |
---|
6382 | % fill-column: 100 % |
---|
6383 | % compile-command: "make" % |
---|
6384 | % End: % |
---|