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