1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -*- Mode: Latex -*- %%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
2 | %% |
---|
3 | %% Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo |
---|
4 | %% |
---|
5 | %% The contents of this file are covered under the licence agreement in the |
---|
6 | %% file "LICENCE" distributed with Cforall. |
---|
7 | %% |
---|
8 | %% user.tex -- |
---|
9 | %% |
---|
10 | %% Author : Peter A. Buhr |
---|
11 | %% Created On : Wed Apr 6 14:53:29 2016 |
---|
12 | %% Last Modified By : Peter A. Buhr |
---|
13 | %% Last Modified On : Sat Jul 22 11:01:19 2017 |
---|
14 | %% Update Count : 2878 |
---|
15 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
16 | |
---|
17 | % requires tex packages: texlive-base texlive-latex-base tex-common texlive-humanities texlive-latex-extra texlive-fonts-recommended |
---|
18 | |
---|
19 | \documentclass[twoside,11pt]{article} |
---|
20 | |
---|
21 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
22 | |
---|
23 | % Latex packages used in the document. |
---|
24 | \usepackage[T1]{fontenc} % allow Latin1 (extended ASCII) characters |
---|
25 | \usepackage{textcomp} |
---|
26 | \usepackage[latin1]{inputenc} |
---|
27 | |
---|
28 | \usepackage{fullpage,times,comment} |
---|
29 | \usepackage{epic,eepic} |
---|
30 | \usepackage{upquote} % switch curled `'" to straight |
---|
31 | \usepackage{calc} |
---|
32 | \usepackage{xspace} |
---|
33 | \usepackage{varioref} % extended references |
---|
34 | \usepackage{listings} % format program code |
---|
35 | \usepackage[flushmargin]{footmisc} % support label/reference in footnote |
---|
36 | \usepackage{latexsym} % \Box glyph |
---|
37 | \usepackage{mathptmx} % better math font with "times" |
---|
38 | \usepackage[usenames]{color} |
---|
39 | \usepackage[pagewise]{lineno} |
---|
40 | \renewcommand{\linenumberfont}{\scriptsize\sffamily} |
---|
41 | \input{common} % common CFA document macros |
---|
42 | \usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,colorlinks=true,pagebackref=true,linkcolor=blue,citecolor=blue,urlcolor=blue,pagebackref=true,breaklinks=true]{hyperref} |
---|
43 | \usepackage{breakurl} |
---|
44 | \renewcommand{\UrlFont}{\small\sf} |
---|
45 | |
---|
46 | % Default underscore is too low and wide. Cannot use lstlisting "literate" as replacing underscore |
---|
47 | % removes it as a variable-name character so keywords in variables are highlighted. MUST APPEAR |
---|
48 | % AFTER HYPERREF. |
---|
49 | \renewcommand{\_}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}} |
---|
50 | \renewcommand{\textunderscore}{\leavevmode\makebox[1.2ex][c]{\rule{1ex}{0.075ex}}} |
---|
51 | |
---|
52 | \setlength{\topmargin}{-0.45in} % move running title into header |
---|
53 | \setlength{\headsep}{0.25in} |
---|
54 | |
---|
55 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
56 | |
---|
57 | \CFAStyle % use default CFA format-style |
---|
58 | |
---|
59 | \lstnewenvironment{C++}[1][] |
---|
60 | {\lstset{language=C++,moredelim=**[is][\protect\color{red}]{®}{®}#1}} |
---|
61 | {} |
---|
62 | |
---|
63 | % inline code ©...© (copyright symbol) emacs: C-q M-) |
---|
64 | % red highlighting ®...® (registered trademark symbol) emacs: C-q M-. |
---|
65 | % blue highlighting ß...ß (sharp s symbol) emacs: C-q M-_ |
---|
66 | % green highlighting ¢...¢ (cent symbol) emacs: C-q M-" |
---|
67 | % LaTex escape §...§ (section symbol) emacs: C-q M-' |
---|
68 | % keyword escape ¶...¶ (pilcrow symbol) emacs: C-q M-^ |
---|
69 | % math escape $...$ (dollar symbol) |
---|
70 | |
---|
71 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
72 | |
---|
73 | % Names used in the document. |
---|
74 | \newcommand{\Version}{\input{../../version}} |
---|
75 | \newcommand{\Textbf}[2][red]{{\color{#1}{\textbf{#2}}}} |
---|
76 | \newcommand{\Emph}[2][red]{{\color{#1}\textbf{\emph{#2}}}} |
---|
77 | \newcommand{\R}[1]{\Textbf{#1}} |
---|
78 | \newcommand{\B}[1]{{\Textbf[blue]{#1}}} |
---|
79 | \newcommand{\G}[1]{{\Textbf[OliveGreen]{#1}}} |
---|
80 | |
---|
81 | \newsavebox{\LstBox} |
---|
82 | |
---|
83 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
84 | |
---|
85 | \setcounter{secnumdepth}{3} % number subsubsections |
---|
86 | \setcounter{tocdepth}{3} % subsubsections in table of contents |
---|
87 | \makeindex |
---|
88 | |
---|
89 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
90 | |
---|
91 | \title{\Huge |
---|
92 | \vspace*{1in} |
---|
93 | \CFA (\CFL) User Manual \\ |
---|
94 | Version 1.0 \\ |
---|
95 | \vspace*{0.25in} |
---|
96 | \huge``describe not prescribe'' |
---|
97 | \vspace*{1in} |
---|
98 | }% title |
---|
99 | |
---|
100 | \author{ |
---|
101 | \huge \CFA Team \medskip \\ |
---|
102 | \Large Andrew Beach, Richard Bilson, Peter A. Buhr, Thierry Delisle, \smallskip \\ |
---|
103 | \Large Glen Ditchfield, Rodolfo G. Esteves, Aaron Moss, Rob Schluntz |
---|
104 | }% author |
---|
105 | |
---|
106 | \date{ |
---|
107 | DRAFT \\ \today |
---|
108 | }% date |
---|
109 | |
---|
110 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
---|
111 | |
---|
112 | \begin{document} |
---|
113 | \pagestyle{headings} |
---|
114 | % changed after setting pagestyle |
---|
115 | \renewcommand{\sectionmark}[1]{\markboth{\thesection\quad #1}{\thesection\quad #1}} |
---|
116 | \renewcommand{\subsectionmark}[1]{\markboth{\thesubsection\quad #1}{\thesubsection\quad #1}} |
---|
117 | \pagenumbering{roman} |
---|
118 | \linenumbers % comment out to turn off line numbering |
---|
119 | |
---|
120 | \maketitle |
---|
121 | \thispagestyle{empty} |
---|
122 | \vspace*{\fill} |
---|
123 | \noindent |
---|
124 | \copyright\,2016 \CFA Project \\ \\ |
---|
125 | \noindent |
---|
126 | This work is licensed under the Creative Commons Attribution 4.0 International License. |
---|
127 | To view a copy of this license, visit {\small\url{http://creativecommons.org/licenses/by/4.0}}. |
---|
128 | \vspace*{1in} |
---|
129 | |
---|
130 | \clearpage |
---|
131 | \thispagestyle{plain} |
---|
132 | \pdfbookmark[1]{Contents}{section} |
---|
133 | \tableofcontents |
---|
134 | |
---|
135 | \clearpage |
---|
136 | \thispagestyle{plain} |
---|
137 | \pagenumbering{arabic} |
---|
138 | |
---|
139 | |
---|
140 | \section{Introduction} |
---|
141 | |
---|
142 | \CFA{}\index{cforall@\CFA}\footnote{Pronounced ``\Index*{C-for-all}'', and written \CFA, CFA, or \CFL.} is a modern general-purpose programming-language, designed as an evolutionary step forward for the C programming language. |
---|
143 | The syntax of \CFA builds from C and should look immediately familiar to C/\Index*[C++]{\CC{}} programmers. |
---|
144 | % Any language feature that is not described here can be assumed to be using the standard \Celeven syntax. |
---|
145 | \CFA adds many modern programming-language features that directly lead to increased \emph{\Index{safety}} and \emph{\Index{productivity}}, while maintaining interoperability with existing C programs and achieving similar performance. |
---|
146 | Like C, \CFA is a statically typed, procedural (non-\Index{object-oriented}) language with a low-overhead runtime, meaning there is no global \Index{garbage-collection}, but \Index{regional garbage-collection}\index{garbage-collection!regional} is possible. |
---|
147 | The primary new features include parametric-polymorphic routines and types, exceptions, concurrency, and modules. |
---|
148 | |
---|
149 | One of the main design philosophies of \CFA is to ``\Index{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''. |
---|
150 | 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. |
---|
151 | A programmer is always free to reach back to C from \CFA, for any reason, and in many cases, new \CFA features can be locally switched back to there C counterpart. |
---|
152 | There is no notion or requirement for \emph{rewriting} a legacy C program in \CFA; |
---|
153 | instead, a programmer evolves a legacy program into \CFA by incrementally incorporating \CFA features. |
---|
154 | As well, new programs can be written in \CFA using a combination of C and \CFA features. |
---|
155 | |
---|
156 | \Index*[C++]{\CC{}} had a similar goal 30 years ago, allowing object-oriented programming to be incrementally added to C. |
---|
157 | However, \CC currently has the disadvantages of a strong object-oriented bias, multiple legacy design-choices that cannot be updated, and active divergence of the language model from C, all of which requires significant effort and training to incrementally add \CC to a C-based project. |
---|
158 | In contrast, \CFA has 30 years of hindsight and a clean starting point. |
---|
159 | |
---|
160 | Like \Index*[C++]{\CC{}}, there may be both an old and new ways to achieve the same effect. |
---|
161 | For example, the following programs compare the \CFA, C, and \CC I/O mechanisms, where the programs output the same result. |
---|
162 | \begin{quote2} |
---|
163 | \begin{tabular}{@{}l@{\hspace{1.5em}}l@{\hspace{1.5em}}l@{}} |
---|
164 | \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{C}} & \multicolumn{1}{c}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{\CC}} \\ |
---|
165 | \begin{cfa} |
---|
166 | #include <stdio.h>§\indexc{stdio.h}§ |
---|
167 | |
---|
168 | int main( void ) { |
---|
169 | int x = 0, y = 1, z = 2; |
---|
170 | ®printf( "%d %d %d\n", x, y, z );® |
---|
171 | } |
---|
172 | \end{cfa} |
---|
173 | & |
---|
174 | \begin{cfa} |
---|
175 | #include <fstream>§\indexc{fstream}§ |
---|
176 | |
---|
177 | int main( void ) { |
---|
178 | int x = 0, y = 1, z = 2; |
---|
179 | ®sout | x | y | z | endl;®§\indexc{sout}§ |
---|
180 | } |
---|
181 | \end{cfa} |
---|
182 | & |
---|
183 | \begin{cfa} |
---|
184 | #include <iostream>§\indexc{iostream}§ |
---|
185 | using namespace std; |
---|
186 | int main() { |
---|
187 | int x = 0, y = 1, z = 2; |
---|
188 | ®cout<<x<<" "<<y<<" "<<z<<endl;® |
---|
189 | } |
---|
190 | \end{cfa} |
---|
191 | \end{tabular} |
---|
192 | \end{quote2} |
---|
193 | While the \CFA I/O looks similar to the \Index*[C++]{\CC{}} output style, there are important differences, such as automatic spacing between variables as in \Index*{Python} (see~\VRef{s:IOLibrary}). |
---|
194 | |
---|
195 | \subsection{Background} |
---|
196 | |
---|
197 | This document is a programmer reference-manual for the \CFA programming language. |
---|
198 | The manual covers the core features of the language and runtime-system, with simple examples illustrating syntax and semantics of each feature. |
---|
199 | The manual does not teach programming, i.e., how to combine the new constructs to build complex programs. |
---|
200 | A reader should already have an intermediate knowledge of control flow, data structures, and concurrency issues to understand the ideas presented, as well as some experience programming in C/\CC. |
---|
201 | Implementers should refer to the \CFA Programming Language Specification for details about the language syntax and semantics. |
---|
202 | Changes to the syntax and additional features are expected to be included in later revisions. |
---|
203 | |
---|
204 | |
---|
205 | \section{Why fix C?} |
---|
206 | |
---|
207 | The C programming language is a foundational technology for modern computing with millions of lines of code implementing everything from commercial operating-systems (especially UNIX systems) to hobby projects. |
---|
208 | This installation base and the programmers producing it represent a massive software-engineering investment spanning decades and likely to continue for decades more. |
---|
209 | Even with all its problems, C continues to be popular because it allows writing software at virtually any level in a computer system without restriction. |
---|
210 | For system programming, where direct access to hardware, storage management, and real-time issues are a requirement, C is usually the only language of choice. |
---|
211 | The TIOBE index~\cite{TIOBE} for March 2016 showed the following programming-language popularity: \Index*{Java} 20.5\%, C 14.5\%, \Index*[C++]{\CC{}} 6.7\%, \Csharp 4.3\%, \Index*{Python} 4.3\%, where the next 50 languages are less than 3\% each with a long tail. |
---|
212 | As well, for 30 years, C has been the number 1 and 2 most popular programming language: |
---|
213 | \begin{center} |
---|
214 | \setlength{\tabcolsep}{1.5ex} |
---|
215 | \begin{tabular}{@{}r|c|c|c|c|c|c|c@{}} |
---|
216 | Ranking & 2016 & 2011 & 2006 & 2001 & 1996 & 1991 & 1986 \\ |
---|
217 | \hline |
---|
218 | Java & 1 & 1 & 1 & 3 & 29 & - & - \\ |
---|
219 | \hline |
---|
220 | \R{C} & \R{2} & \R{2} & \R{2} & \R{1} & \R{1} & \R{1} & \R{1} \\ |
---|
221 | \hline |
---|
222 | \CC & 3 & 3 & 3 & 2 & 2 & 2 & 7 \\ |
---|
223 | \end{tabular} |
---|
224 | \end{center} |
---|
225 | Hence, C is still an extremely important programming language, with double the usage of \Index*[C++]{\CC{}}; in many cases, \CC is often used solely as a better C. |
---|
226 | Love it or hate it, C has been an important and influential part of computer science for 40 years and its appeal is not diminishing. |
---|
227 | Unfortunately, C has many problems and omissions that make it an unacceptable programming language for modern needs. |
---|
228 | |
---|
229 | As stated, the goal of the \CFA project is to engineer modern language-features into C in an evolutionary rather than revolutionary way. |
---|
230 | \CC~\cite{C++14,C++} is an example of a similar project; |
---|
231 | however, it largely extended the C language, and did not address most of C's existing problems.\footnote{% |
---|
232 | Two important existing problems addressed were changing the type of character literals from ©int© to ©char© and enumerator from ©int© to the type of its enumerators.} |
---|
233 | \Index*{Fortran}~\cite{Fortran08}, \Index*{Ada}~\cite{Ada12}, and \Index*{Cobol}~\cite{Cobol14} are examples of programming languages that took an evolutionary approach, where modern language-features (\eg objects, concurrency) are added and problems fixed within the framework of the existing language. |
---|
234 | \Index*{Java}~\cite{Java8}, \Index*{Go}~\cite{Go}, \Index*{Rust}~\cite{Rust} and \Index*{D}~\cite{D} are examples of the revolutionary approach for modernizing C/\CC, resulting in a new language rather than an extension of the descendent. |
---|
235 | These languages have different syntax and semantics from C, do not interoperate directly with C, and are not systems languages because of restrictive memory-management or garbage collection. |
---|
236 | As a result, there is a significant learning curve to move to these languages, and C legacy-code must be rewritten. |
---|
237 | These costs can be prohibitive for many companies with a large software-base in C/\CC, and a significant number of programmers require retraining to the new programming language. |
---|
238 | |
---|
239 | The result of this project is a language that is largely backwards compatible with \Index*[C11]{\Celeven{}}~\cite{C11}, but fixes many of the well known C problems while containing modern language-features. |
---|
240 | Without significant extension to the C programming language, it is becoming unable to cope with the needs of modern programming problems and programmers; |
---|
241 | as a result, it will fade into disuse. |
---|
242 | Considering the large body of existing C code and programmers, there is significant impetus to ensure C is transformed into a modern programming language. |
---|
243 | While \Index*[C11]{\Celeven{}} made a few simple extensions to the language, nothing was added to address existing problems in the language or to augment the language with modern language-features. |
---|
244 | 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. |
---|
245 | |
---|
246 | |
---|
247 | \section{History} |
---|
248 | |
---|
249 | The \CFA project started with \Index*{K-W C}~\cite{Buhr94a,Till89}, which extended C with new declaration syntax, multiple return values from routines, and advanced assignment capabilities using the notion of tuples. |
---|
250 | (See~\cite{Werther96} for similar work in \Index*[C++]{\CC{}}.) |
---|
251 | The first \CFA implementation of these extensions was by Esteves~\cite{Esteves04}. |
---|
252 | |
---|
253 | The signature feature of \CFA is \emph{\Index{overload}able} \Index{parametric-polymorphic} functions~\cite{forceone:impl,Cormack90,Duggan96} with functions generalized using a ©forall© clause (giving the language its name): |
---|
254 | \begin{lstlisting} |
---|
255 | ®forall( otype T )® T identity( T val ) { return val; } |
---|
256 | int forty_two = identity( 42 ); §\C{// T is bound to int, forty\_two == 42}§ |
---|
257 | \end{lstlisting} |
---|
258 | % extending the C type system with parametric polymorphism and overloading, as opposed to the \Index*[C++]{\CC{}} approach of object-oriented extensions. |
---|
259 | \CFA{}\hspace{1pt}'s polymorphism was originally formalized by Ditchfield~\cite{Ditchfield92}, and first implemented by Bilson~\cite{Bilson03}. |
---|
260 | However, at that time, there was little interesting in extending C, so work did not continue. |
---|
261 | As the saying goes, ``\Index*{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. |
---|
262 | |
---|
263 | |
---|
264 | \section{Interoperability} |
---|
265 | \label{s:Interoperability} |
---|
266 | |
---|
267 | \CFA is designed to integrate directly with existing C programs and libraries. |
---|
268 | The most important feature of \Index{interoperability} is using the same \Index{calling convention}s, so there is no complex interface or overhead to call existing C routines. |
---|
269 | This feature allows \CFA programmers to take advantage of the existing panoply of C libraries to access thousands of external software features. |
---|
270 | Language developers often state that adequate \Index{library support} takes more work than designing and implementing the language itself. |
---|
271 | Fortunately, \CFA, like \Index*[C++]{\CC{}}, starts with immediate access to all exiting C libraries, and in many cases, can easily wrap library routines with simpler and safer interfaces, at very low cost. |
---|
272 | Hence, \CFA begins by leveraging the large repository of C libraries, and than allows programmers to incrementally augment their C programs with modern \Index{backward-compatible} features. |
---|
273 | |
---|
274 | \begin{comment} |
---|
275 | A simple example is leveraging the existing type-unsafe (©void *©) C ©bsearch© to binary search a sorted floating-point array: |
---|
276 | \begin{lstlisting} |
---|
277 | void * bsearch( const void * key, const void * base, size_t dim, size_t size, |
---|
278 | int (* compar)( const void *, const void * )); |
---|
279 | |
---|
280 | int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 : |
---|
281 | *(double *)t2 < *(double *)t1 ? 1 : 0; } |
---|
282 | |
---|
283 | double key = 5.0, vals[10] = { /* 10 sorted floating-point values */ }; |
---|
284 | double * val = (double *)bsearch( &key, vals, 10, sizeof(vals[0]), comp ); $\C{// search sorted array}$ |
---|
285 | \end{lstlisting} |
---|
286 | which can be augmented simply with a polymorphic, type-safe, \CFA-overloaded wrappers: |
---|
287 | \begin{lstlisting} |
---|
288 | forall( otype T | { int ?<?( T, T ); } ) T * bsearch( T key, const T * arr, size_t size ) { |
---|
289 | int comp( const void * t1, const void * t2 ) { /* as above with double changed to T */ } |
---|
290 | return (T *)bsearch( &key, arr, size, sizeof(T), comp ); } |
---|
291 | |
---|
292 | forall( otype T | { int ?<?( T, T ); } ) unsigned int bsearch( T key, const T * arr, size_t size ) { |
---|
293 | T * result = bsearch( key, arr, size ); $\C{// call first version}$ |
---|
294 | return result ? result - arr : size; } $\C{// pointer subtraction includes sizeof(T)}$ |
---|
295 | |
---|
296 | double * val = bsearch( 5.0, vals, 10 ); $\C{// selection based on return type}$ |
---|
297 | int posn = bsearch( 5.0, vals, 10 ); |
---|
298 | \end{lstlisting} |
---|
299 | The nested function ©comp© provides the hidden interface from typed \CFA to untyped (©void *©) C, plus the cast of the result. |
---|
300 | Providing a hidden ©comp© function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope. |
---|
301 | As well, an alternate kind of return is made available: position versus pointer to found element. |
---|
302 | \CC's type-system cannot disambiguate between the two versions of ©bsearch© because it does not use the return type in overload resolution, nor can \CC separately compile a templated ©bsearch©. |
---|
303 | |
---|
304 | \CFA has replacement libraries condensing hundreds of existing C functions into tens of \CFA overloaded functions, all without rewriting the actual computations. |
---|
305 | For example, it is possible to write a type-safe \CFA wrapper ©malloc© based on the C ©malloc©: |
---|
306 | \begin{lstlisting} |
---|
307 | forall( dtype T | sized(T) ) T * malloc( void ) { return (T *)malloc( sizeof(T) ); } |
---|
308 | int * ip = malloc(); §\C{// select type and size from left-hand side}§ |
---|
309 | double * dp = malloc(); |
---|
310 | struct S {...} * sp = malloc(); |
---|
311 | \end{lstlisting} |
---|
312 | where the return type supplies the type/size of the allocation, which is impossible in most type systems. |
---|
313 | \end{comment} |
---|
314 | |
---|
315 | However, it is necessary to differentiate between C and \CFA code because of name \Index{overload}ing, as for \CC. |
---|
316 | For example, the C math-library provides the following routines for computing the absolute value of the basic types: ©abs©, ©labs©, ©llabs©, ©fabs©, ©fabsf©, ©fabsl©, ©cabsf©, ©cabs©, and ©cabsl©. |
---|
317 | Whereas, \CFA wraps each of these routines into ones with the overloaded name ©abs©: |
---|
318 | \begin{cfa} |
---|
319 | char abs( char ); |
---|
320 | ®extern "C" {® int abs( int ); ®}® §\C{// use default C routine for int}§ |
---|
321 | long int abs( long int ); |
---|
322 | long long int abs( long long int ); |
---|
323 | float abs( float ); |
---|
324 | double abs( double ); |
---|
325 | long double abs( long double ); |
---|
326 | float _Complex abs( float _Complex ); |
---|
327 | double _Complex abs( double _Complex ); |
---|
328 | long double _Complex abs( long double _Complex ); |
---|
329 | \end{cfa} |
---|
330 | The problem is the name clash between the library routine ©abs© and the \CFA names ©abs©. |
---|
331 | Hence, names appearing in an ©extern "C"© block have \newterm*{C linkage}. |
---|
332 | Then overloading polymorphism uses a mechanism called \newterm{name mangling}\index{mangling!name} to create unique names that are different from C names, which are not mangled. |
---|
333 | 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. |
---|
334 | There is no way around this problem, other than C's approach of creating unique names for each pairing of operation and type. |
---|
335 | |
---|
336 | This example strongly illustrates a core idea in \CFA: \emph{the \Index{power of a name}}. |
---|
337 | The name ``©abs©'' evokes the notion of absolute value, and many mathematical types provide the notion of absolute value. |
---|
338 | Hence, knowing the name ©abs© is sufficient to apply it to any type where it is applicable. |
---|
339 | The time savings and safety of using one name uniformly versus $N$ unique names cannot be underestimated. |
---|
340 | |
---|
341 | |
---|
342 | \section[Compiling a CFA Program]{Compiling a \CFA Program} |
---|
343 | |
---|
344 | The command ©cfa© is used to compile a \CFA program and is based on the \Index{GNU} \Indexc{gcc} command, \eg: |
---|
345 | \begin{cfa} |
---|
346 | cfa§\indexc{cfa}\index{compilation!cfa@©cfa©}§ [ gcc-options ] C/§\CFA{}§-files [ assembler/loader-files ] |
---|
347 | \end{cfa} |
---|
348 | \CFA programs having the following ©gcc© flags turned on: |
---|
349 | \begin{description} |
---|
350 | \item |
---|
351 | \Indexc{-std=gnu99}\index{compilation option!-std=gnu99@{©-std=gnu99©}} |
---|
352 | The 1999 C standard plus GNU extensions. |
---|
353 | \item |
---|
354 | \Indexc[deletekeywords=inline]{-fgnu89-inline}\index{compilation option!-fgnu89-inline@{\lstinline[deletekeywords=inline]$-fgnu89-inline$}} |
---|
355 | Use the traditional GNU semantics for inline routines in C99 mode, which allows inline routines in header files. |
---|
356 | \end{description} |
---|
357 | The following new \CFA options are available: |
---|
358 | \begin{description} |
---|
359 | \item |
---|
360 | \Indexc{-CFA}\index{compilation option!-CFA@©-CFA©} |
---|
361 | 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. |
---|
362 | The generated code starts with the standard \CFA \Index{prelude}. |
---|
363 | |
---|
364 | \item |
---|
365 | \Indexc{-debug}\index{compilation option!-debug@©-debug©} |
---|
366 | The program is linked with the debugging version of the runtime system. |
---|
367 | The debug version performs runtime checks to help during the debugging phase of a \CFA program, but can substantially slow program execution. |
---|
368 | The runtime checks should only be removed after the program is completely debugged. |
---|
369 | \textbf{This option is the default.} |
---|
370 | |
---|
371 | \item |
---|
372 | \Indexc{-nodebug}\index{compilation option!-nodebug@©-nodebug©} |
---|
373 | The program is linked with the non-debugging version of the runtime system, so the execution of the program is faster. |
---|
374 | \Emph{However, no runtime checks or ©assert©s are performed so errors usually result in abnormal program behaviour or termination.} |
---|
375 | |
---|
376 | \item |
---|
377 | \Indexc{-help}\index{compilation option!-help@©-help©} |
---|
378 | Information about the set of \CFA compilation flags is printed. |
---|
379 | |
---|
380 | \item |
---|
381 | \Indexc{-nohelp}\index{compilation option!-nohelp@©-nohelp©} |
---|
382 | Information about the set of \CFA compilation flags is not printed. |
---|
383 | \textbf{This option is the default.} |
---|
384 | |
---|
385 | \item |
---|
386 | \Indexc{-quiet}\index{compilation option!-quiet@©-quiet©} |
---|
387 | The \CFA compilation message is not printed at the beginning of a compilation. |
---|
388 | |
---|
389 | \item |
---|
390 | \Indexc{-noquiet}\index{compilation option!-noquiet@©-noquiet©} |
---|
391 | The \CFA compilation message is printed at the beginning of a compilation. |
---|
392 | \textbf{This option is the default.} |
---|
393 | |
---|
394 | \begin{comment} |
---|
395 | \item |
---|
396 | \Indexc{-no-include-stdhdr}\index{compilation option!-no-include-stdhdr@©-no-include-stdhdr©} |
---|
397 | Do not supply ©extern "C"© wrappers for \Celeven standard include files (see~\VRef{s:StandardHeaders}). |
---|
398 | \textbf{This option is \emph{not} the default.} |
---|
399 | \end{comment} |
---|
400 | \end{description} |
---|
401 | |
---|
402 | The following preprocessor variables are available: |
---|
403 | \begin{description} |
---|
404 | \item |
---|
405 | \Indexc{__CFA_MAJOR__}\index{preprocessor variables!__CFA__@{©__CFA__©}} |
---|
406 | is available during preprocessing and its value is the major \Index{version number} of \CFA.\footnote{ |
---|
407 | The C preprocessor allows only integer values in a preprocessor variable so a value like ``\Version'' is not allowed. |
---|
408 | Hence, the need to have three variables for the major, minor and patch version number.} |
---|
409 | |
---|
410 | \item |
---|
411 | \Indexc{__CFA_MINOR__}\index{preprocessor variables!__CFA_MINOR__@{©__CFA_MINOR__©}} |
---|
412 | is available during preprocessing and its value is the minor \Index{version number} of \CFA. |
---|
413 | |
---|
414 | \item |
---|
415 | \Indexc{__CFA_PATCH__}\index{preprocessor variables!__CFA_PATCH__@©__CFA_PATCH__©} |
---|
416 | is available during preprocessing and its value is the patch \Index{level number} of \CFA. |
---|
417 | |
---|
418 | \item |
---|
419 | \Indexc{__CFA__}\index{preprocessor variables!__CFA__@©__CFA__©}, |
---|
420 | \Indexc{__CFORALL__}\index{preprocessor variables!__CFORALL__@©__CFORALL__©}, and |
---|
421 | \Indexc{__cforall}\index{preprocessor variables!__cforall@©__cforall©} |
---|
422 | are always available during preprocessing and have no value. |
---|
423 | \end{description} |
---|
424 | These preprocessor variables allow conditional compilation of programs that must work differently in these situations. |
---|
425 | For example, to toggle between C and \CFA extensions, use the following: |
---|
426 | \begin{cfa} |
---|
427 | #ifndef __CFORALL__ |
---|
428 | #include <stdio.h>§\indexc{stdio.h}§ §\C{// C header file}§ |
---|
429 | #else |
---|
430 | #include <fstream>§\indexc{fstream}§ §\C{// \CFA header file}§ |
---|
431 | #endif |
---|
432 | \end{cfa} |
---|
433 | which conditionally includes the correct header file, if the program is compiled using \Indexc{gcc} or \Indexc{cfa}. |
---|
434 | |
---|
435 | |
---|
436 | \section{Constant Underscores} |
---|
437 | |
---|
438 | Numeric constants are extended to allow \Index{underscore}s\index{constant!underscore}, \eg: |
---|
439 | \begin{cfa} |
---|
440 | 2®_®147®_®483®_®648; §\C{// decimal constant}§ |
---|
441 | 56®_®ul; §\C{// decimal unsigned long constant}§ |
---|
442 | 0®_®377; §\C{// octal constant}§ |
---|
443 | 0x®_®ff®_®ff; §\C{// hexadecimal constant}§ |
---|
444 | 0x®_®ef3d®_®aa5c; §\C{// hexadecimal constant}§ |
---|
445 | 3.141®_®592®_®654; §\C{// floating point constant}§ |
---|
446 | 10®_®e®_®+1®_®00; §\C{// floating point constant}§ |
---|
447 | 0x®_®ff®_®ff®_®p®_®3; §\C{// hexadecimal floating point}§ |
---|
448 | 0x®_®1.ffff®_®ffff®_®p®_®128®_®l; §\C{// hexadecimal floating point long constant}§ |
---|
449 | L®_®§"\texttt{\textbackslash{x}}§®_®§\texttt{ff}§®_®§\texttt{ee}"§; §\C{// wide character constant}§ |
---|
450 | \end{cfa} |
---|
451 | The rules for placement of underscores are: |
---|
452 | \begin{enumerate}[topsep=5pt,itemsep=5pt,parsep=0pt] |
---|
453 | \item |
---|
454 | A sequence of underscores is disallowed, \eg ©12__34© is invalid. |
---|
455 | \item |
---|
456 | Underscores may only appear within a sequence of digits (regardless of the digit radix). |
---|
457 | In other words, an underscore cannot start or end a sequence of digits, \eg ©_1©, ©1_© and ©_1_© are invalid (actually, the 1st and 3rd examples are identifier names). |
---|
458 | \item |
---|
459 | A numeric prefix may end with an underscore; |
---|
460 | a numeric infix may begin and/or end with an underscore; |
---|
461 | a numeric suffix may begin with an underscore. |
---|
462 | For example, the octal ©0© or hexadecimal ©0x© prefix may end with an underscore ©0_377© or ©0x_ff©; |
---|
463 | the exponent infix ©E© may start or end with an underscore ©1.0_E10©, ©1.0E_10© or ©1.0_E_10©; |
---|
464 | the type suffixes ©U©, ©L©, etc. may start with an underscore ©1_U©, ©1_ll© or ©1.0E10_f©. |
---|
465 | \end{enumerate} |
---|
466 | It is significantly easier to read and enter long constants when they are broken up into smaller groupings (many cultures use comma and/or period among digits for the same purpose). |
---|
467 | This extension is backwards compatible, matches with the use of underscore in variable names, and appears in \Index*{Ada} and \Index*{Java} 8. |
---|
468 | |
---|
469 | |
---|
470 | \section{Backquote Identifiers} |
---|
471 | \label{s:BackquoteIdentifiers} |
---|
472 | |
---|
473 | \CFA introduces several new keywords (see \VRef{s:CFAKeywords}) that can clash with existing C variable-names in legacy code. |
---|
474 | Keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism: |
---|
475 | \begin{cfa} |
---|
476 | int ®`®otype®`® = 3; §\C{// make keyword an identifier}§ |
---|
477 | double ®`®forall®`® = 3.5; |
---|
478 | \end{cfa} |
---|
479 | |
---|
480 | Existing C programs with keyword clashes can be converted by enclosing keyword identifiers in backquotes, and eventually the identifier name can be changed to a non-keyword name. |
---|
481 | \VRef[Figure]{f:HeaderFileInterposition} shows how clashes in existing C header-files (see~\VRef{s:StandardHeaders}) can be handled using preprocessor \newterm{interposition}: ©#include_next© and ©-I filename©. |
---|
482 | Several common C header-files with keyword clashes are fixed in the standard \CFA header-library, so there is a seamless programming-experience. |
---|
483 | |
---|
484 | \begin{figure} |
---|
485 | \begin{cfa} |
---|
486 | // include file uses the CFA keyword "with". |
---|
487 | #if ! defined( with ) §\C{// nesting ?}§ |
---|
488 | #define with ®`®with®`® §\C{// make keyword an identifier}§ |
---|
489 | #define __CFA_BFD_H__ |
---|
490 | #endif |
---|
491 | |
---|
492 | ®#include_next <bfdlink.h> §\C{// must have internal check for multiple expansion}§ |
---|
493 | ® |
---|
494 | #if defined( with ) && defined( __CFA_BFD_H__ ) §\C{// reset only if set}§ |
---|
495 | #undef with |
---|
496 | #undef __CFA_BFD_H__ |
---|
497 | #endif |
---|
498 | \end{cfa} |
---|
499 | \caption{Header-File Interposition} |
---|
500 | \label{f:HeaderFileInterposition} |
---|
501 | \end{figure} |
---|
502 | |
---|
503 | |
---|
504 | \section{\texorpdfstring{Labelled \LstKeywordStyle{continue} / \LstKeywordStyle{break}}{Labelled continue / break}} |
---|
505 | |
---|
506 | While C provides ©continue© and ©break© statements for altering control flow, both are restricted to one level of nesting for a particular control structure. |
---|
507 | Unfortunately, this restriction forces programmers to use \Indexc{goto} to achieve the equivalent control-flow for more than one level of nesting. |
---|
508 | To prevent having to switch to the ©goto©, \CFA extends the \Indexc{continue}\index{continue@\lstinline $continue$!labelled}\index{labelled!continue@©continue©} and \Indexc{break}\index{break@\lstinline $break$!labelled}\index{labelled!break@©break©} with a target label to support static multi-level exit\index{multi-level exit}\index{static multi-level exit}~\cite{Buhr85}, as in Java. |
---|
509 | For both ©continue© and ©break©, the target label must be directly associated with a ©for©, ©while© or ©do© statement; |
---|
510 | for ©break©, the target label can also be associated with a ©switch©, ©if© or compound (©{}©) statement. |
---|
511 | \VRef[Figure]{f:MultiLevelResumeTermination} shows the labelled ©continue© and ©break©, specifying which control structure is the target for exit, and the corresponding C program using only ©goto©. |
---|
512 | The innermost loop has 7 exit points, which cause resumption or termination of one or more of the 7 \Index{nested control-structure}s. |
---|
513 | |
---|
514 | \begin{figure} |
---|
515 | \begin{tabular}{@{\hspace{\parindentlnth}}l@{\hspace{1.5em}}l@{}} |
---|
516 | \multicolumn{1}{c@{\hspace{1.5em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
517 | \begin{cfa} |
---|
518 | ®LC:® { |
---|
519 | ... §declarations§ ... |
---|
520 | ®LS:® switch ( ... ) { |
---|
521 | case 3: |
---|
522 | ®LIF:® if ( ... ) { |
---|
523 | ®LF:® for ( ... ) { |
---|
524 | ®LW:® while ( ... ) { |
---|
525 | ... break ®LC®; ... // terminate compound |
---|
526 | ... break ®LS®; ... // terminate switch |
---|
527 | ... break ®LIF®; ... // terminate if |
---|
528 | ... continue ®LF;® ... // resume loop |
---|
529 | ... break ®LF®; ... // terminate loop |
---|
530 | ... continue ®LW®; ... // resume loop |
---|
531 | ... break ®LW®; ... // terminate loop |
---|
532 | } // while |
---|
533 | } // for |
---|
534 | } else { |
---|
535 | ... break ®LIF®; ... // terminate if |
---|
536 | } // if |
---|
537 | } // switch |
---|
538 | } // compound |
---|
539 | \end{cfa} |
---|
540 | & |
---|
541 | \begin{cfa} |
---|
542 | { |
---|
543 | ... §declarations§ ... |
---|
544 | switch ( ... ) { |
---|
545 | case 3: |
---|
546 | if ( ... ) { |
---|
547 | for ( ... ) { |
---|
548 | while ( ... ) { |
---|
549 | ... goto ®LC®; ... |
---|
550 | ... goto ®LS®; ... |
---|
551 | ... goto ®LIF®; ... |
---|
552 | ... goto ®LFC®; ... |
---|
553 | ... goto ®LFB®; ... |
---|
554 | ... goto ®LWC®; ... |
---|
555 | ... goto ®LWB®; ... |
---|
556 | ®LWC®: ; } ®LWB:® ; |
---|
557 | ®LFC:® ; } ®LFB:® ; |
---|
558 | } else { |
---|
559 | ... goto ®LIF®; ... |
---|
560 | } ®L3:® ; |
---|
561 | } ®LS:® ; |
---|
562 | } ®LC:® ; |
---|
563 | \end{cfa} |
---|
564 | \end{tabular} |
---|
565 | \caption{Multi-level Resume/Termination} |
---|
566 | \label{f:MultiLevelResumeTermination} |
---|
567 | \end{figure} |
---|
568 | |
---|
569 | \begin{comment} |
---|
570 | int main() { |
---|
571 | LC: { |
---|
572 | LS: switch ( 1 ) { |
---|
573 | case 3: |
---|
574 | LIF: if ( 1 ) { |
---|
575 | LF: for ( ;; ) { |
---|
576 | LW: while ( 1 ) { |
---|
577 | break LC; // terminate compound |
---|
578 | break LS; // terminate switch |
---|
579 | break LIF; // terminate if |
---|
580 | continue LF; // resume loop |
---|
581 | break LF; // terminate loop |
---|
582 | continue LW; // resume loop |
---|
583 | break LW; // terminate loop |
---|
584 | } // while |
---|
585 | } // for |
---|
586 | } else { |
---|
587 | break LIF; // terminate if |
---|
588 | } // if |
---|
589 | } // switch |
---|
590 | } // compound |
---|
591 | { |
---|
592 | switch ( 1 ) { |
---|
593 | case 3: |
---|
594 | if ( 1 ) { |
---|
595 | for ( ;; ) { |
---|
596 | while ( 1 ) { |
---|
597 | goto LCx; |
---|
598 | goto LSx; |
---|
599 | goto LIF; |
---|
600 | goto LFC; |
---|
601 | goto LFB; |
---|
602 | goto LWC; |
---|
603 | goto LWB; |
---|
604 | LWC: ; } LWB: ; |
---|
605 | LFC: ; } LFB: ; |
---|
606 | } else { |
---|
607 | goto LIF; |
---|
608 | } L3: ; |
---|
609 | } LSx: ; |
---|
610 | } LCx: ; |
---|
611 | } |
---|
612 | |
---|
613 | // Local Variables: // |
---|
614 | // tab-width: 4 // |
---|
615 | // End: // |
---|
616 | \end{comment} |
---|
617 | |
---|
618 | |
---|
619 | Both labelled ©continue© and ©break© are a ©goto©\index{goto@\lstinline $goto$!restricted} restricted in the following ways: |
---|
620 | \begin{itemize} |
---|
621 | \item |
---|
622 | They cannot create a loop, which means only the looping constructs cause looping. |
---|
623 | This restriction means all situations resulting in repeated execution are clearly delineated. |
---|
624 | \item |
---|
625 | They cannot branch into a control structure. |
---|
626 | This restriction prevents missing declarations and/or initializations at the start of a control structure resulting in undefined behaviour. |
---|
627 | \end{itemize} |
---|
628 | The advantage of the labelled ©continue©/©break© is allowing static multi-level exits without having to use the ©goto© statement, and tying control flow to the target control structure rather than an arbitrary point in a program. |
---|
629 | Furthermore, the location of the label at the \emph{beginning} of the target control structure informs the reader (\Index{eye candy}) that complex control-flow is occurring in the body of the control structure. |
---|
630 | With ©goto©, the label is at the end of the control structure, which fails to convey this important clue early enough to the reader. |
---|
631 | Finally, using an explicit target for the transfer instead of an implicit target allows new constructs to be added or removed without affecting existing constructs. |
---|
632 | The implicit targets of the current ©continue© and ©break©, \ie the closest enclosing loop or ©switch©, change as certain constructs are added or removed. |
---|
633 | |
---|
634 | |
---|
635 | \section{\texorpdfstring{\LstKeywordStyle{switch} Statement}{switch Statement}} |
---|
636 | |
---|
637 | C allows a number of questionable forms for the ©switch© statement: |
---|
638 | \begin{enumerate} |
---|
639 | \item |
---|
640 | By default, the end of a ©case© clause\footnote{ |
---|
641 | In this section, the term \emph{case clause} refers to either a ©case© or ©default© clause.} |
---|
642 | \emph{falls through} to the next ©case© clause in the ©switch© statement; |
---|
643 | to exit a ©switch© statement from a ©case© clause requires explicitly terminating the clause with a transfer statement, most commonly ©break©: |
---|
644 | \begin{cfa} |
---|
645 | switch ( i ) { |
---|
646 | case 1: |
---|
647 | ... |
---|
648 | // fall-through |
---|
649 | case 2: |
---|
650 | ... |
---|
651 | break; // exit switch statement |
---|
652 | } |
---|
653 | \end{cfa} |
---|
654 | The ability to fall-through to the next clause \emph{is} a useful form of control flow, specifically when a sequence of case actions compound: |
---|
655 | \begin{quote2} |
---|
656 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
657 | \begin{cfa} |
---|
658 | switch ( argc ) { |
---|
659 | case 3: |
---|
660 | // open output file |
---|
661 | // fall-through |
---|
662 | case 2: |
---|
663 | // open input file |
---|
664 | break; // exit switch statement |
---|
665 | default: |
---|
666 | // usage message |
---|
667 | } |
---|
668 | \end{cfa} |
---|
669 | & |
---|
670 | \begin{cfa} |
---|
671 | |
---|
672 | if ( argc == 3 ) { |
---|
673 | // open output file |
---|
674 | ®// open input file |
---|
675 | ®} else if ( argc == 2 ) { |
---|
676 | ®// open input file (duplicate) |
---|
677 | |
---|
678 | ®} else { |
---|
679 | // usage message |
---|
680 | } |
---|
681 | \end{cfa} |
---|
682 | \end{tabular} |
---|
683 | \end{quote2} |
---|
684 | In this example, case 2 is always done if case 3 is done. |
---|
685 | This control flow is difficult to simulate with if statements or a ©switch© statement without fall-through as code must be duplicated or placed in a separate routine. |
---|
686 | C also uses fall-through to handle multiple case-values resulting in the same action: |
---|
687 | \begin{cfa} |
---|
688 | switch ( i ) { |
---|
689 | ®case 1: case 3: case 5:® // odd values |
---|
690 | // odd action |
---|
691 | break; |
---|
692 | ®case 2: case 4: case 6:® // even values |
---|
693 | // even action |
---|
694 | break; |
---|
695 | } |
---|
696 | \end{cfa} |
---|
697 | However, this situation is handled in other languages without fall-through by allowing a list of case values. |
---|
698 | While fall-through itself is not a problem, the problem occurs when fall-through is the default, as this semantics is unintuitive to many programmers and is different from virtually all other programming languages with a ©switch© statement. |
---|
699 | Hence, default fall-through semantics results in a large number of programming errors as programmers often \emph{forget} the ©break© statement at the end of a ©case© clause, resulting in inadvertent fall-through. |
---|
700 | |
---|
701 | \item |
---|
702 | It is possible to place ©case© clauses on statements nested \emph{within} the body of the ©switch© statement: |
---|
703 | \begin{cfa} |
---|
704 | switch ( i ) { |
---|
705 | case 0: |
---|
706 | if ( j < k ) { |
---|
707 | ... |
---|
708 | ®case 1:® // transfer into "if" statement |
---|
709 | ... |
---|
710 | } // if |
---|
711 | case 2: |
---|
712 | while ( j < 5 ) { |
---|
713 | ... |
---|
714 | ®case 3:® // transfer into "while" statement |
---|
715 | ... |
---|
716 | } // while |
---|
717 | } // switch |
---|
718 | \end{cfa} |
---|
719 | The problem with this usage is branching into control structures, which is known to cause both comprehension and technical difficulties. |
---|
720 | The comprehension problem occurs from the inability to determine how control reaches a particular point due to the number of branches leading to it. |
---|
721 | The technical problem results from the inability to ensure declaration and initialization of variables when blocks are not entered at the beginning. |
---|
722 | There are no positive arguments for this kind of control flow, and therefore, there is a strong impetus to eliminate it. |
---|
723 | Nevertheless, C does have an idiom where this capability is used, known as ``\Index*{Duff's device}''~\cite{Duff83}: |
---|
724 | \begin{cfa} |
---|
725 | register int n = (count + 7) / 8; |
---|
726 | switch ( count % 8 ) { |
---|
727 | case 0: do{ *to = *from++; |
---|
728 | case 7: *to = *from++; |
---|
729 | case 6: *to = *from++; |
---|
730 | case 5: *to = *from++; |
---|
731 | case 4: *to = *from++; |
---|
732 | case 3: *to = *from++; |
---|
733 | case 2: *to = *from++; |
---|
734 | case 1: *to = *from++; |
---|
735 | } while ( --n > 0 ); |
---|
736 | } |
---|
737 | \end{cfa} |
---|
738 | which unrolls a loop N times (N = 8 above) and uses the ©switch© statement to deal with any iterations not a multiple of N. |
---|
739 | While efficient, this sort of special purpose usage is questionable: |
---|
740 | \begin{quote} |
---|
741 | Disgusting, no? But it compiles and runs just fine. I feel a combination of pride and revulsion at this |
---|
742 | discovery.~\cite{Duff83} |
---|
743 | \end{quote} |
---|
744 | \item |
---|
745 | It is possible to place the ©default© clause anywhere in the list of labelled clauses for a ©switch© statement, rather than only at the end. |
---|
746 | Virtually all programming languages with a ©switch© statement require the ©default© clause to appear last in the case-clause list. |
---|
747 | The logic for this semantics is that after checking all the ©case© clauses without success, the ©default© clause is selected; |
---|
748 | hence, physically placing the ©default© clause at the end of the ©case© clause list matches with this semantics. |
---|
749 | This physical placement can be compared to the physical placement of an ©else© clause at the end of a series of connected ©if©/©else© statements. |
---|
750 | |
---|
751 | \item |
---|
752 | It is possible to place unreachable code at the start of a ©switch© statement, as in: |
---|
753 | \begin{cfa} |
---|
754 | switch ( x ) { |
---|
755 | ®int y = 1;® §\C{// unreachable initialization}§ |
---|
756 | ®x = 7;® §\C{// unreachable code without label/branch}§ |
---|
757 | case 3: ... |
---|
758 | ... |
---|
759 | ®int z = 0;® §\C{// unreachable initialization, cannot appear after case}§ |
---|
760 | z = 2; |
---|
761 | case 3: |
---|
762 | ®x = z;® §\C{// without fall through, z is uninitialized}§ |
---|
763 | } |
---|
764 | \end{cfa} |
---|
765 | While the declaration of the local variable ©y© is useful with a scope across all ©case© clauses, the initialization for such a variable is defined to never be executed because control always transfers over it. |
---|
766 | Furthermore, any statements before the first ©case© clause can only be executed if labelled and transferred to using a ©goto©, either from outside or inside of the ©switch©, both of which are problematic. |
---|
767 | As well, the declaration of ©z© cannot occur after the ©case© because a label can only be attached to a statement, and without a fall through to case 3, ©z© is uninitialized. |
---|
768 | The key observation is that the ©switch© statement branches into control structure, \ie there are multiple entry points into its statement body. |
---|
769 | \end{enumerate} |
---|
770 | |
---|
771 | Before discussing potential language changes to deal with these problems, it is worth observing that in a typical C program: |
---|
772 | \begin{itemize} |
---|
773 | \item |
---|
774 | the number of ©switch© statements is small, |
---|
775 | \item |
---|
776 | most ©switch© statements are well formed (\ie no \Index*{Duff's device}), |
---|
777 | \item |
---|
778 | the ©default© clause is usually written as the last case-clause, |
---|
779 | \item |
---|
780 | and there is only a medium amount of fall-through from one ©case© clause to the next, and most of these result from a list of case values executing common code, rather than a sequence of case actions that compound. |
---|
781 | \end{itemize} |
---|
782 | These observations put into perspective the \CFA changes to the ©switch©. |
---|
783 | \begin{enumerate} |
---|
784 | \item |
---|
785 | Eliminating default fall-through has the greatest potential for affecting existing code. |
---|
786 | However, even if fall-through is removed, most ©switch© statements would continue to work because of the explicit transfers already present at the end of each ©case© clause, the common placement of the ©default© clause at the end of the case list, and the most common use of fall-through, \ie a list of ©case© clauses executing common code, \eg: |
---|
787 | \begin{cfa} |
---|
788 | case 1: case 2: case 3: ... |
---|
789 | \end{cfa} |
---|
790 | still works. |
---|
791 | 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. |
---|
792 | Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called ©choose©, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword ©fallthrough©/©fallthru©, \eg: |
---|
793 | \begin{cfa} |
---|
794 | ®choose® ( i ) { |
---|
795 | case 1: case 2: case 3: |
---|
796 | ... |
---|
797 | ®// implicit end of switch (break) |
---|
798 | ®case 5: |
---|
799 | ... |
---|
800 | ®fallthru®; §\C{// explicit fall through}§ |
---|
801 | case 7: |
---|
802 | ... |
---|
803 | ®break® §\C{// redundant explicit end of switch}§ |
---|
804 | default: |
---|
805 | j = 3; |
---|
806 | } |
---|
807 | \end{cfa} |
---|
808 | Like the ©switch© statement, the ©choose© statement retains the fall-through semantics for a list of ©case© clauses; |
---|
809 | An implicit ©break© is applied only at the end of the \emph{statements} following a ©case© clause. |
---|
810 | An explicit ©fallthru© is retained because it is a C-idiom most C programmers expect, and its absence might discourage programmers from using the ©choose© statement. |
---|
811 | As well, allowing an explicit ©break© from the ©choose© is a carry over from the ©switch© statement, and expected by C programmers. |
---|
812 | \item |
---|
813 | \Index*{Duff's device} is eliminated from both ©switch© and ©choose© statements, and only invalidates a small amount of very questionable code. |
---|
814 | Hence, the ©case© clause must appear at the same nesting level as the ©switch©/©choose© body, as is done in most other programming languages with ©switch© statements. |
---|
815 | \item |
---|
816 | The issue of ©default© at locations other than at the end of the cause clause can be solved by using good programming style, and there are a few reasonable situations involving fall-through where the ©default© clause needs to appear is locations other than at the end. |
---|
817 | Therefore, no change is made for this issue. |
---|
818 | \item |
---|
819 | Dealing with unreachable code in a ©switch©/©choose© body is solved by restricting declarations and associated initialization to the start of statement body, which is executed \emph{before} the transfer to the appropriate ©case© clause\footnote{ |
---|
820 | Essentially, these declarations are hoisted before the ©switch©/©choose© statement and both declarations and statement are surrounded by a compound statement.} and precluding statements before the first ©case© clause. |
---|
821 | Further declarations at the same nesting level as the statement body are disallowed to ensure every transfer into the body is sound. |
---|
822 | \begin{cfa} |
---|
823 | switch ( x ) { |
---|
824 | ®int i = 0;® §\C{// allowed only at start}§ |
---|
825 | case 0: |
---|
826 | ... |
---|
827 | ®int j = 0;® §\C{// disallowed}§ |
---|
828 | case 1: |
---|
829 | { |
---|
830 | ®int k = 0;® §\C{// allowed at different nesting levels}§ |
---|
831 | ... |
---|
832 | } |
---|
833 | ... |
---|
834 | } |
---|
835 | \end{cfa} |
---|
836 | \end{enumerate} |
---|
837 | |
---|
838 | |
---|
839 | \section{\texorpdfstring{\LstKeywordStyle{case} Clause}{case Clause}} |
---|
840 | |
---|
841 | C restricts the ©case© clause of a ©switch© statement to a single value. |
---|
842 | For multiple ©case© clauses associated with the same statement, it is necessary to have multiple ©case© clauses rather than multiple values. |
---|
843 | Requiring a ©case© clause for each value does not seem to be in the spirit of brevity normally associated with C. |
---|
844 | Therefore, the ©case© clause is extended with a list of values, as in: |
---|
845 | \begin{quote2} |
---|
846 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
847 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
848 | \begin{cfa} |
---|
849 | switch ( i ) { |
---|
850 | case ®1, 3, 5®: |
---|
851 | ... |
---|
852 | case ®2, 4, 6®: |
---|
853 | ... |
---|
854 | } |
---|
855 | \end{cfa} |
---|
856 | & |
---|
857 | \begin{cfa} |
---|
858 | switch ( i ) { |
---|
859 | case 1: case 3 : case 5: |
---|
860 | ... |
---|
861 | case 2: case 4 : case 6: |
---|
862 | ... |
---|
863 | } |
---|
864 | \end{cfa} |
---|
865 | & |
---|
866 | \begin{cfa} |
---|
867 | |
---|
868 | // odd values |
---|
869 | |
---|
870 | // even values |
---|
871 | |
---|
872 | |
---|
873 | \end{cfa} |
---|
874 | \end{tabular} |
---|
875 | \end{quote2} |
---|
876 | In addition, two forms of subranges are allowed to specify case values: a new \CFA form and an existing GNU C form.\footnote{ |
---|
877 | The GNU C form \emph{requires} spaces around the ellipse.} |
---|
878 | \begin{quote2} |
---|
879 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
880 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{GNU C}} \\ |
---|
881 | \begin{cfa} |
---|
882 | switch ( i ) { |
---|
883 | case ®1~5:® |
---|
884 | ... |
---|
885 | case ®10~15:® |
---|
886 | ... |
---|
887 | } |
---|
888 | \end{cfa} |
---|
889 | & |
---|
890 | \begin{cfa} |
---|
891 | switch ( i ) |
---|
892 | case ®1 ... 5®: |
---|
893 | ... |
---|
894 | case ®10 ... 15®: |
---|
895 | ... |
---|
896 | } |
---|
897 | \end{cfa} |
---|
898 | & |
---|
899 | \begin{cfa} |
---|
900 | |
---|
901 | // 1, 2, 3, 4, 5 |
---|
902 | |
---|
903 | // 10, 11, 12, 13, 14, 15 |
---|
904 | |
---|
905 | |
---|
906 | \end{cfa} |
---|
907 | \end{tabular} |
---|
908 | \end{quote2} |
---|
909 | Lists of subranges are also allowed. |
---|
910 | \begin{cfa} |
---|
911 | case ®1~5, 12~21, 35~42®: |
---|
912 | \end{cfa} |
---|
913 | |
---|
914 | |
---|
915 | \section{\texorpdfstring{\LstKeywordStyle{with} Clause / Statement}{with Clause / Statement}} |
---|
916 | \label{s:WithClauseStatement} |
---|
917 | |
---|
918 | In \Index{object-oriented} programming, there is an implicit first parameter, often names \textbf{©self©} or \textbf{©this©}, which is elided. |
---|
919 | \begin{C++} |
---|
920 | class C { |
---|
921 | int i, j; |
---|
922 | int mem() { ®// implicit "this" parameter |
---|
923 | ® i = 1; ®// this->i |
---|
924 | ® j = 3; ®// this->j |
---|
925 | ® } |
---|
926 | } |
---|
927 | \end{C++} |
---|
928 | Since CFA is non-object-oriented, the equivalent object-oriented program looks like: |
---|
929 | \begin{cfa} |
---|
930 | struct S { int i, j; }; |
---|
931 | int mem( S &this ) { // explicit "this" parameter |
---|
932 | ®this.®i = 1; // "this" is not elided |
---|
933 | ®this.®j = 2; |
---|
934 | } |
---|
935 | \end{cfa} |
---|
936 | but it is cumbersome having to write "©this.©" many times in a member. |
---|
937 | |
---|
938 | \CFA provides a ©with© clause/statement (see Pascal~\cite[\S~4.F]{Pascal}) to elided the "©this.©" by opening a scope containing field identifiers, changing the qualified fields into variables and giving an opportunity for optimizing qualified references. |
---|
939 | \begin{cfa} |
---|
940 | int mem( S &this ) ®with this® { // with clause |
---|
941 | i = 1; ®// this.i |
---|
942 | ® j = 2; ®// this.j |
---|
943 | ®} |
---|
944 | \end{cfa} |
---|
945 | which extends to multiple routine parameters: |
---|
946 | \begin{cfa} |
---|
947 | struct T { double m, n; }; |
---|
948 | int mem2( S &this1, T &this2 ) ®with this1, this2® { |
---|
949 | i = 1; j = 2; |
---|
950 | m = 1.0; n = 2.0; |
---|
951 | } |
---|
952 | \end{cfa} |
---|
953 | |
---|
954 | The statement form is used within a block: |
---|
955 | \begin{cfa} |
---|
956 | int foo() { |
---|
957 | struct S1 { ... } s1; |
---|
958 | struct S2 { ... } s2; |
---|
959 | ®with s1® { // with statement |
---|
960 | // access fields of s1 without qualification |
---|
961 | ®with s2® { // nesting |
---|
962 | // access fields of s1 and s2 without qualification |
---|
963 | } |
---|
964 | } |
---|
965 | ®with s1, s2® { |
---|
966 | // access unambiguous fields of s1 and s2 without qualification |
---|
967 | } |
---|
968 | } |
---|
969 | \end{cfa} |
---|
970 | |
---|
971 | When opening multiple structures, fields with the same name and type are ambiguous and must be fully qualified. |
---|
972 | For fields with the same name but different type, context/cast can be used to disambiguate. |
---|
973 | \begin{cfa} |
---|
974 | struct S { int i; int j; double m; } a, c; |
---|
975 | struct T { int i; int k; int m } b, c; |
---|
976 | ®with a, b® { |
---|
977 | j + k; §\C{// unambiguous, unique names define unique types}§ |
---|
978 | i; §\C{// ambiguous, same name and type}§ |
---|
979 | a.i + b.i; §\C{// unambiguous, qualification defines unique names}§ |
---|
980 | m; §\C{// ambiguous, same name and no context to define unique type}§ |
---|
981 | m = 5.0; §\C{// unambiguous, same name and context defines unique type}§ |
---|
982 | m = 1; §\C{// unambiguous, same name and context defines unique type}§ |
---|
983 | } |
---|
984 | ®with c® { ... } §\C{// ambiguous, same name and no context}§ |
---|
985 | ®with (S)c® { ... } §\C{// unambiguous, same name and cast defines unique type}§ |
---|
986 | \end{cfa} |
---|
987 | |
---|
988 | |
---|
989 | \section{Exception Handling} |
---|
990 | \label{s:ExceptionHandling} |
---|
991 | |
---|
992 | Exception handling provides two mechanism: change of control flow from a raise to a handler, and communication from the raise to the handler. |
---|
993 | Transfer of control can be local, within a routine, or non-local, among routines. |
---|
994 | Non-local transfer can cause stack unwinding, i.e., non-local routine termination, depending on the kind of raise. |
---|
995 | \begin{cfa} |
---|
996 | exception_t E {}; §\C{// exception type}§ |
---|
997 | void f(...) { |
---|
998 | ... throw E{}; ... §\C{// termination}§ |
---|
999 | ... throwResume E{}; ... §\C{// resumption}§ |
---|
1000 | } |
---|
1001 | try { |
---|
1002 | f(...); |
---|
1003 | } catch( E e : §boolean-predicate§ ) { §\C{// termination handler}§ |
---|
1004 | // recover and continue |
---|
1005 | } catchResume( E e : §boolean-predicate§ ) { §\C{// resumption handler}§ |
---|
1006 | // repair and return |
---|
1007 | } finally { |
---|
1008 | // always executed |
---|
1009 | } |
---|
1010 | \end{cfa} |
---|
1011 | The kind of raise and handler match: ©throw© with ©catch© and ©throwResume© with ©catchResume©. |
---|
1012 | Then the exception type must match along with any additonal predicate must be true. |
---|
1013 | The ©catch© and ©catchResume© handlers may appear in any oder. |
---|
1014 | However, the ©finally© clause must appear at the end of the ©try© statement. |
---|
1015 | |
---|
1016 | |
---|
1017 | \subsection{Exception Hierarchy} |
---|
1018 | |
---|
1019 | An exception type can be derived from another exception type, just like deriving a subclass from a class, providing a kind of polymorphism among exception types. |
---|
1020 | The exception-type hierarchy that is created is used to organize exception types, similar to a class hierarchy in object-oriented languages, \eg: |
---|
1021 | \begin{center} |
---|
1022 | \input{EHMHierarchy} |
---|
1023 | \end{center} |
---|
1024 | A programmer can then choose to handle an exception at different degrees of specificity along the hierarchy; |
---|
1025 | derived exception-types support a more flexible programming style. |
---|
1026 | For example, higher-level code should catch general exceptions to reduce coupling to the specific implementation at the lower levels; |
---|
1027 | unnecessary coupling may force changes in higher-level code when low-level code changes. |
---|
1028 | A consequence of derived exception-types is that multiple exceptions may match, \eg: |
---|
1029 | \begin{cfa} |
---|
1030 | catch( Arithmetic ) |
---|
1031 | \end{cfa} |
---|
1032 | matches all three derived exception-types: ©DivideByZero©, ©Overflow©, and ©Underflow©. |
---|
1033 | Because the propagation mechanisms perform a simple linear search of the handler clause for a guarded block, and selects the first matching handler, the order of catch clauses in the handler clause becomes important, \eg: |
---|
1034 | \begin{cfa} |
---|
1035 | try { |
---|
1036 | ... |
---|
1037 | } catch( Overflow ) { // must appear first |
---|
1038 | // handle overflow |
---|
1039 | } catch( Arithmetic ) |
---|
1040 | // handle other arithmetic issues |
---|
1041 | } |
---|
1042 | \end{cfa} |
---|
1043 | \newterm{Multiple derivation} among exception is not supported. |
---|
1044 | |
---|
1045 | |
---|
1046 | \section{Declarations} |
---|
1047 | \label{s:Declarations} |
---|
1048 | |
---|
1049 | C declaration syntax is notoriously confusing and error prone. |
---|
1050 | For example, many C programmers are confused by a declaration as simple as: |
---|
1051 | \begin{quote2} |
---|
1052 | \begin{tabular}{@{}ll@{}} |
---|
1053 | \begin{cfa} |
---|
1054 | int * x[5] |
---|
1055 | \end{cfa} |
---|
1056 | & |
---|
1057 | \raisebox{-0.75\totalheight}{\input{Cdecl}} |
---|
1058 | \end{tabular} |
---|
1059 | \end{quote2} |
---|
1060 | Is this an array of 5 pointers to integers or a \Index{pointer} to an array of 5 integers? |
---|
1061 | The fact this declaration is unclear to many C programmers means there are \Index{productivity} and \Index{safety} issues even for basic programs. |
---|
1062 | 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. |
---|
1063 | For example, a routine returning a \Index{pointer} to an array of integers is defined and used in the following way: |
---|
1064 | \begin{cfa} |
---|
1065 | int ®(*®f®())[®5®]® {...}; §\C{definition}§ |
---|
1066 | ... ®(*®f®())[®3®]® += 1; §\C{usage}§ |
---|
1067 | \end{cfa} |
---|
1068 | Essentially, the return type is wrapped around the routine name in successive layers (like an \Index{onion}). |
---|
1069 | While attempting to make the two contexts consistent is a laudable goal, it has not worked out in practice. |
---|
1070 | |
---|
1071 | \CFA provides its own type, variable and routine declarations, using a different syntax. |
---|
1072 | The new declarations place qualifiers to the left of the base type, while C declarations place qualifiers to the right of the base type. |
---|
1073 | In the following example, \R{red} is the base type and \B{blue} is qualifiers. |
---|
1074 | The \CFA declarations move the qualifiers to the left of the base type, \ie move the blue to the left of the red, while the qualifiers have the same meaning but are ordered left to right to specify a variable's type. |
---|
1075 | \begin{quote2} |
---|
1076 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1077 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1078 | \begin{cfa} |
---|
1079 | ß[5] *ß ®int® x1; |
---|
1080 | ß* [5]ß ®int® x2; |
---|
1081 | ß[* [5] int]ß f®( int p )®; |
---|
1082 | \end{cfa} |
---|
1083 | & |
---|
1084 | \begin{cfa} |
---|
1085 | ®int® ß*ß x1 ß[5]ß; |
---|
1086 | ®int® ß(*ßx2ß)[5]ß; |
---|
1087 | ßint (*ßf®( int p )®ß)[5]ß; |
---|
1088 | \end{cfa} |
---|
1089 | \end{tabular} |
---|
1090 | \end{quote2} |
---|
1091 | The only exception is \Index{bit field} specification, which always appear to the right of the base type. |
---|
1092 | % Specifically, the character ©*© is used to indicate a pointer, square brackets ©[©\,©]© are used to represent an array or function return value, and parentheses ©()© are used to indicate a routine parameter. |
---|
1093 | However, unlike C, \CFA type declaration tokens are distributed across all variables in the declaration list. |
---|
1094 | For instance, variables ©x© and ©y© of type \Index{pointer} to integer are defined in \CFA as follows: |
---|
1095 | \begin{quote2} |
---|
1096 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1097 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1098 | \begin{cfa} |
---|
1099 | ®*® int x, y; |
---|
1100 | \end{cfa} |
---|
1101 | & |
---|
1102 | \begin{cfa} |
---|
1103 | int ®*®x, ®*®y; |
---|
1104 | \end{cfa} |
---|
1105 | \end{tabular} |
---|
1106 | \end{quote2} |
---|
1107 | The downside of this semantics is the need to separate regular and \Index{pointer} declarations: |
---|
1108 | \begin{quote2} |
---|
1109 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1110 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1111 | \begin{cfa} |
---|
1112 | ®*® int x; |
---|
1113 | int y; |
---|
1114 | \end{cfa} |
---|
1115 | & |
---|
1116 | \begin{cfa} |
---|
1117 | int ®*®x, y; |
---|
1118 | |
---|
1119 | \end{cfa} |
---|
1120 | \end{tabular} |
---|
1121 | \end{quote2} |
---|
1122 | which is \Index{prescribing} a safety benefit. |
---|
1123 | Other examples are: |
---|
1124 | \begin{quote2} |
---|
1125 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
1126 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
1127 | \begin{cfa} |
---|
1128 | [ 5 ] int z; |
---|
1129 | [ 5 ] * char w; |
---|
1130 | * [ 5 ] double v; |
---|
1131 | struct s { |
---|
1132 | int f0:3; |
---|
1133 | * int f1; |
---|
1134 | [ 5 ] * int f2; |
---|
1135 | }; |
---|
1136 | \end{cfa} |
---|
1137 | & |
---|
1138 | \begin{cfa} |
---|
1139 | int z[ 5 ]; |
---|
1140 | char * w[ 5 ]; |
---|
1141 | double (* v)[ 5 ]; |
---|
1142 | struct s { |
---|
1143 | int f0:3; |
---|
1144 | int * f1; |
---|
1145 | int * f2[ 5 ] |
---|
1146 | }; |
---|
1147 | \end{cfa} |
---|
1148 | & |
---|
1149 | \begin{cfa} |
---|
1150 | // array of 5 integers |
---|
1151 | // array of 5 pointers to char |
---|
1152 | // pointer to array of 5 doubles |
---|
1153 | |
---|
1154 | // common bit field syntax |
---|
1155 | |
---|
1156 | |
---|
1157 | |
---|
1158 | \end{cfa} |
---|
1159 | \end{tabular} |
---|
1160 | \end{quote2} |
---|
1161 | |
---|
1162 | All type qualifiers, \eg ©const©, ©volatile©, etc., are used in the normal way with the new declarations and also appear left to right, \eg: |
---|
1163 | \begin{quote2} |
---|
1164 | \begin{tabular}{@{}l@{\hspace{1em}}l@{\hspace{1em}}l@{}} |
---|
1165 | \multicolumn{1}{c@{\hspace{1em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{1em}}}{\textbf{C}} \\ |
---|
1166 | \begin{cfa} |
---|
1167 | const * const int x; |
---|
1168 | const * [ 5 ] const int y; |
---|
1169 | \end{cfa} |
---|
1170 | & |
---|
1171 | \begin{cfa} |
---|
1172 | int const * const x; |
---|
1173 | const int (* const y)[ 5 ] |
---|
1174 | \end{cfa} |
---|
1175 | & |
---|
1176 | \begin{cfa} |
---|
1177 | // const pointer to const integer |
---|
1178 | // const pointer to array of 5 const integers |
---|
1179 | \end{cfa} |
---|
1180 | \end{tabular} |
---|
1181 | \end{quote2} |
---|
1182 | All declaration qualifiers, \eg ©extern©, ©static©, etc., are used in the normal way with the new declarations but can only appear at the start of a \CFA routine declaration,\footnote{\label{StorageClassSpecifier} |
---|
1183 | The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature.~\cite[\S~6.11.5(1)]{C11}} \eg: |
---|
1184 | \begin{quote2} |
---|
1185 | \begin{tabular}{@{}l@{\hspace{3em}}l@{\hspace{2em}}l@{}} |
---|
1186 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c@{\hspace{2em}}}{\textbf{C}} \\ |
---|
1187 | \begin{cfa} |
---|
1188 | extern [ 5 ] int x; |
---|
1189 | static * const int y; |
---|
1190 | \end{cfa} |
---|
1191 | & |
---|
1192 | \begin{cfa} |
---|
1193 | int extern x[ 5 ]; |
---|
1194 | const int static * y; |
---|
1195 | \end{cfa} |
---|
1196 | & |
---|
1197 | \begin{cfa} |
---|
1198 | // externally visible array of 5 integers |
---|
1199 | // internally visible pointer to constant int |
---|
1200 | \end{cfa} |
---|
1201 | \end{tabular} |
---|
1202 | \end{quote2} |
---|
1203 | |
---|
1204 | The new declaration syntax can be used in other contexts where types are required, \eg casts and the pseudo-routine ©sizeof©: |
---|
1205 | \begin{quote2} |
---|
1206 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1207 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1208 | \begin{cfa} |
---|
1209 | y = (®* int®)x; |
---|
1210 | i = sizeof(®[ 5 ] * int®); |
---|
1211 | \end{cfa} |
---|
1212 | & |
---|
1213 | \begin{cfa} |
---|
1214 | y = (®int *®)x; |
---|
1215 | i = sizeof(®int * [ 5 ]®); |
---|
1216 | \end{cfa} |
---|
1217 | \end{tabular} |
---|
1218 | \end{quote2} |
---|
1219 | |
---|
1220 | Finally, new \CFA declarations may appear together with C declarations in the same program block, but cannot be mixed within a specific declaration. |
---|
1221 | Therefore, a programmer has the option of either continuing to use traditional C declarations or take advantage of the new style. |
---|
1222 | Clearly, both styles need to be supported for some time due to existing C-style header-files, particularly for UNIX systems. |
---|
1223 | |
---|
1224 | |
---|
1225 | \section{Exponentiation Operator} |
---|
1226 | |
---|
1227 | C, \CC, and Java (and many other programming languages) have no exponentiation operator\index{exponentiation!operator}\index{operator!exponentiation}, \ie $x^y$, and instead use a routine, like \Indexc{pow}, to perform the exponentiation operation. |
---|
1228 | \CFA extends the basic operators with the exponentiation operator ©?\?©\index{?\\?@\lstinline$?\?$} and ©?\=?©\index{?\\=?@\lstinline$?\=?$}, as in, ©x \ y© and ©x \= y©, which means $x^y$ and $x \leftarrow x^y$. |
---|
1229 | The priority of the exponentiation operator is between the cast and multiplicative operators, so that ©w * (int)x \ (int)y * z© is parenthesized as ©((w * (((int)x) \ ((int)y))) * z)©. |
---|
1230 | |
---|
1231 | As for \Index{division}, there are exponentiation operators for integral and floating-point types, including the builtin \Index{complex} types. |
---|
1232 | Unsigned integral exponentiation\index{exponentiation!unsigned integral} is performed with repeated multiplication (or shifting if the base is 2). |
---|
1233 | Signed integral exponentiation\index{exponentiation!signed integral} is performed with repeated multiplication (or shifting if the base is 2), but yields a floating-point result because $b^{-e}=1/b^e$. |
---|
1234 | Hence, it is important to designate exponent integral-constants as unsigned or signed: ©3 \ 3u© return an integral result, while ©3 \ 3© returns a floating-point result. |
---|
1235 | Floating-point exponentiation\index{exponentiation!floating point} is performed using \Index{logarithm}s\index{exponentiation!logarithm}, so the base cannot be negative. |
---|
1236 | \begin{cfa} |
---|
1237 | sout | 2 ®\® 8u | 4 ®\® 3u | -4 ®\® 3u | 4 ®\® -3 | -4 ®\® -3 | 4.0 ®\® 2.1 | (1.0f+2.0fi) ®\® (3.0f+2.0fi) | endl; |
---|
1238 | 256 64 -64 0.015625 -0.015625 18.3791736799526 0.264715-1.1922i |
---|
1239 | \end{cfa} |
---|
1240 | Parenthesis are necessary for the complex constants or the expresion is parsed as ©1.0f+(2.0fi \ 3.0f)+2.0fi©. |
---|
1241 | The exponentiation operator is available for all the basic types, but for user-defined types, only the integral-computation versions are available. |
---|
1242 | For returning an integral value, the user type ©T© must define multiplication, ©*©, and one, ©1©; |
---|
1243 | for returning a floating-point value, an additional divide of type ©T© into a ©double© returning a ©double© (©double ?/?( double, T )©) is necessary for negative exponents. |
---|
1244 | |
---|
1245 | |
---|
1246 | \section{Pointer / Reference} |
---|
1247 | |
---|
1248 | C provides a \newterm{pointer type}; |
---|
1249 | \CFA adds a \newterm{reference type}. |
---|
1250 | These types may be derived from an object or routine type, called the \newterm{referenced type}. |
---|
1251 | Objects of these types contain an \newterm{address}, which is normally a location in memory, but may also address memory-mapped registers in hardware devices. |
---|
1252 | An integer constant expression with the value 0, or such an expression cast to type ©void *©, is called a \newterm{null-pointer constant}.\footnote{ |
---|
1253 | One way to conceptualize the null pointer is that no variable is placed at this address, so the null-pointer address can be used to denote an uninitialized pointer/reference object; |
---|
1254 | \ie the null pointer is guaranteed to compare unequal to a pointer to any object or routine. |
---|
1255 | In general, a value with special meaning among a set of values is called a \emph{\Index{sentinel value}}, \eg ©-1© as a return code value.} |
---|
1256 | An address is \newterm{sound}, if it points to a valid memory location in scope, \ie within the program's execution-environment and has not been freed. |
---|
1257 | Dereferencing an \newterm{unsound} address, including the null pointer, is \Index{undefined}, often resulting in a \Index{memory fault}. |
---|
1258 | |
---|
1259 | A program \newterm{object} is a region of data storage in the execution environment, the contents of which can represent values. |
---|
1260 | In most cases, objects are located in memory at an address, and the variable name for an object is an implicit address to the object generated by the compiler and automatically dereferenced, as in: |
---|
1261 | \begin{quote2} |
---|
1262 | \begin{tabular}{@{}ll@{\hspace{2em}}l@{}} |
---|
1263 | \begin{cfa} |
---|
1264 | int x; |
---|
1265 | x = 3; |
---|
1266 | int y; |
---|
1267 | y = x; |
---|
1268 | \end{cfa} |
---|
1269 | & |
---|
1270 | \raisebox{-0.45\totalheight}{\input{pointer1}} |
---|
1271 | & |
---|
1272 | \begin{cfa} |
---|
1273 | int * ®const® x = (int *)100 |
---|
1274 | *x = 3; // implicit dereference |
---|
1275 | int * ®const® y = (int *)104; |
---|
1276 | *y = *x; // implicit dereference |
---|
1277 | \end{cfa} |
---|
1278 | \end{tabular} |
---|
1279 | \end{quote2} |
---|
1280 | where the right example is how the compiler logically interprets the variables in the left example. |
---|
1281 | Since a variable name only points to one address during its lifetime, it is an \Index{immutable} \Index{pointer}; |
---|
1282 | hence, the implicit type of pointer variables ©x© and ©y© are constant pointers in the compiler interpretation. |
---|
1283 | In general, variable addresses are stored in instructions instead of loaded from memory, and hence may not occupy storage. |
---|
1284 | These approaches are contrasted in the following: |
---|
1285 | \begin{quote2} |
---|
1286 | \begin{tabular}{@{}l|l@{}} |
---|
1287 | \multicolumn{1}{c|}{explicit variable address} & \multicolumn{1}{c}{implicit variable address} \\ |
---|
1288 | \hline |
---|
1289 | \begin{cfa} |
---|
1290 | lda r1,100 // load address of x |
---|
1291 | ld r2,(r1) // load value of x |
---|
1292 | lda r3,104 // load address of y |
---|
1293 | st r2,(r3) // store x into y |
---|
1294 | \end{cfa} |
---|
1295 | & |
---|
1296 | \begin{cfa} |
---|
1297 | |
---|
1298 | ld r2,(100) // load value of x |
---|
1299 | |
---|
1300 | st r2,(104) // store x into y |
---|
1301 | \end{cfa} |
---|
1302 | \end{tabular} |
---|
1303 | \end{quote2} |
---|
1304 | Finally, the immutable nature of a variable's address and the fact that there is no storage for the variable pointer means pointer assignment\index{pointer!assignment}\index{assignment!pointer} is impossible. |
---|
1305 | Therefore, the expression ©x = y© has only one meaning, ©*x = *y©, \ie manipulate values, which is why explicitly writing the dereferences is unnecessary even though it occurs implicitly as part of \Index{instruction decoding}. |
---|
1306 | |
---|
1307 | A \Index{pointer}/\Index{reference} object is a generalization of an object variable-name, \ie a mutable address that can point to more than one memory location during its lifetime. |
---|
1308 | (Similarly, an integer variable can contain multiple integer literals during its lifetime versus an integer constant representing a single literal during its lifetime, and like a variable name, may not occupy storage if the literal is embedded directly into instructions.) |
---|
1309 | Hence, a pointer occupies memory to store its current address, and the pointer's value is loaded by dereferencing, \eg: |
---|
1310 | \begin{quote2} |
---|
1311 | \begin{tabular}{@{}l@{\hspace{2em}}l@{}} |
---|
1312 | \begin{cfa} |
---|
1313 | int x, y, ®*® p1, ®*® p2, ®**® p3; |
---|
1314 | p1 = ®&®x; // p1 points to x |
---|
1315 | p2 = p1; // p2 points to x |
---|
1316 | p1 = ®&®y; // p1 points to y |
---|
1317 | p3 = &p2; // p3 points to p2 |
---|
1318 | \end{cfa} |
---|
1319 | & |
---|
1320 | \raisebox{-0.5\totalheight}{\input{pointer2.pstex_t}} |
---|
1321 | \end{tabular} |
---|
1322 | \end{quote2} |
---|
1323 | |
---|
1324 | Notice, an address has a \Index{duality}\index{address!duality}: a location in memory or the value at that location. |
---|
1325 | In many cases, a compiler might be able to infer the best meaning for these two cases. |
---|
1326 | For example, \Index*{Algol68}~\cite{Algol68} infers pointer dereferencing to select the best meaning for each pointer usage |
---|
1327 | \begin{cfa} |
---|
1328 | p2 = p1 + x; §\C{// compiler infers *p2 = *p1 + x;}§ |
---|
1329 | \end{cfa} |
---|
1330 | Algol68 infers the following dereferencing ©*p2 = *p1 + x©, because adding the arbitrary integer value in ©x© to the address of ©p1© and storing the resulting address into ©p2© is an unlikely operation. |
---|
1331 | Unfortunately, automatic dereferencing does not work in all cases, and so some mechanism is necessary to fix incorrect choices. |
---|
1332 | |
---|
1333 | Rather than inferring dereference, most programming languages pick one implicit dereferencing semantics, and the programmer explicitly indicates the other to resolve address-duality. |
---|
1334 | In C, objects of pointer type always manipulate the pointer object's address: |
---|
1335 | \begin{cfa} |
---|
1336 | p1 = p2; §\C{// p1 = p2\ \ rather than\ \ *p1 = *p2}§ |
---|
1337 | p2 = p1 + x; §\C{// p2 = p1 + x\ \ rather than\ \ *p2 = *p1 + x}§ |
---|
1338 | \end{cfa} |
---|
1339 | even though the assignment to ©p2© is likely incorrect, and the programmer probably meant: |
---|
1340 | \begin{cfa} |
---|
1341 | p1 = p2; §\C{// pointer address assignment}§ |
---|
1342 | ®*®p2 = ®*®p1 + x; §\C{// pointed-to value assignment / operation}§ |
---|
1343 | \end{cfa} |
---|
1344 | The C semantics work well for situations where manipulation of addresses is the primary meaning and data is rarely accessed, such as storage management (©malloc©/©free©). |
---|
1345 | |
---|
1346 | However, in most other situations, the pointed-to value is requested more often than the pointer address. |
---|
1347 | \begin{cfa} |
---|
1348 | *p2 = ((*p1 + *p2) * (**p3 - *p1)) / (**p3 - 15); |
---|
1349 | \end{cfa} |
---|
1350 | In this case, it is tedious to explicitly write the dereferencing, and error prone when pointer arithmetic is allowed. |
---|
1351 | It is better to have the compiler generate the dereferencing and have no implicit pointer arithmetic: |
---|
1352 | \begin{cfa} |
---|
1353 | p2 = ((p1 + p2) * (p3 - p1)) / (p3 - 15); |
---|
1354 | \end{cfa} |
---|
1355 | |
---|
1356 | To support this common case, a reference type is introduced in \CFA, denoted by ©&©, which is the opposite dereference semantics to a pointer type, making the value at the pointed-to location the implicit semantics for dereferencing (similar but not the same as \CC \Index{reference type}s). |
---|
1357 | \begin{cfa} |
---|
1358 | int x, y, ®&® r1, ®&® r2, ®&&® r3; |
---|
1359 | ®&®r1 = &x; §\C{// r1 points to x}§ |
---|
1360 | ®&®r2 = &r1; §\C{// r2 points to x}§ |
---|
1361 | ®&®r1 = &y; §\C{// r1 points to y}§ |
---|
1362 | ®&&®r3 = ®&®&r2; §\C{// r3 points to r2}§ |
---|
1363 | r2 = ((r1 + r2) * (r3 - r1)) / (r3 - 15); §\C{// implicit dereferencing}§ |
---|
1364 | \end{cfa} |
---|
1365 | Except for auto-dereferencing by the compiler, this reference example is the same as the previous pointer example. |
---|
1366 | Hence, a reference behaves like the variable name for the current variable it is pointing-to. |
---|
1367 | One way to conceptualize a reference is via a rewrite rule, where the compiler inserts a dereference operator before the reference variable for each reference qualifier in a declaration, so the previous example becomes: |
---|
1368 | \begin{cfa} |
---|
1369 | ®*®r2 = ((®*®r1 + ®*®r2) ®*® (®**®r3 - ®*®r1)) / (®**®r3 - 15); |
---|
1370 | \end{cfa} |
---|
1371 | When a reference operation appears beside a dereference operation, \eg ©&*©, they cancel out. |
---|
1372 | However, in C, the cancellation always yields a value (\Index{rvalue}).\footnote{ |
---|
1373 | The unary ©&© operator yields the address of its operand. |
---|
1374 | If the operand has type ``type'', the result has type ``pointer to type''. |
---|
1375 | If the operand is the result of a unary ©*© operator, neither that operator nor the ©&© operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.~\cite[\S~6.5.3.2--3]{C11}} |
---|
1376 | For a \CFA reference type, the cancellation on the left-hand side of assignment leaves the reference as an address (\Index{lvalue}): |
---|
1377 | \begin{cfa} |
---|
1378 | (&®*®)r1 = &x; §\C{// (\&*) cancel giving address in r1 not variable pointed-to by r1}§ |
---|
1379 | \end{cfa} |
---|
1380 | Similarly, the address of a reference can be obtained for assignment or computation (\Index{rvalue}): |
---|
1381 | \begin{cfa} |
---|
1382 | (&(&®*®)®*®)r3 = &(&®*®)r2; §\C{// (\&*) cancel giving address in r2, (\&(\&*)*) cancel giving address in r3}§ |
---|
1383 | \end{cfa} |
---|
1384 | Cancellation\index{cancellation!pointer/reference}\index{pointer!cancellation} works to arbitrary depth. |
---|
1385 | |
---|
1386 | Fundamentally, pointer and reference objects are functionally interchangeable because both contain addresses. |
---|
1387 | \begin{cfa} |
---|
1388 | int x, *p1 = &x, **p2 = &p1, ***p3 = &p2, |
---|
1389 | &r1 = x, &&r2 = r1, &&&r3 = r2; |
---|
1390 | ***p3 = 3; §\C{// change x}§ |
---|
1391 | r3 = 3; §\C{// change x, ***r3}§ |
---|
1392 | **p3 = ...; §\C{// change p1}§ |
---|
1393 | &r3 = ...; §\C{// change r1, (\&*)**r3, 1 cancellation}§ |
---|
1394 | *p3 = ...; §\C{// change p2}§ |
---|
1395 | &&r3 = ...; §\C{// change r2, (\&(\&*)*)*r3, 2 cancellations}§ |
---|
1396 | &&&r3 = p3; §\C{// change r3 to p3, (\&(\&(\&*)*)*)r3, 3 cancellations}§ |
---|
1397 | \end{cfa} |
---|
1398 | Furthermore, both types are equally performant, as the same amount of dereferencing occurs for both types. |
---|
1399 | Therefore, the choice between them is based solely on whether the address is dereferenced frequently or infrequently, which dictates the amount of implicit dereferencing aid from the compiler. |
---|
1400 | |
---|
1401 | As for a pointer type, a reference type may have qualifiers: |
---|
1402 | \begin{cfa} |
---|
1403 | const int cx = 5; §\C{// cannot change cx;}§ |
---|
1404 | const int & cr = cx; §\C{// cannot change what cr points to}§ |
---|
1405 | ®&®cr = &cx; §\C{// can change cr}§ |
---|
1406 | cr = 7; §\C{// error, cannot change cx}§ |
---|
1407 | int & const rc = x; §\C{// must be initialized}§ |
---|
1408 | ®&®rc = &x; §\C{// error, cannot change rc}§ |
---|
1409 | const int & const crc = cx; §\C{// must be initialized}§ |
---|
1410 | crc = 7; §\C{// error, cannot change cx}§ |
---|
1411 | ®&®crc = &cx; §\C{// error, cannot change crc}§ |
---|
1412 | \end{cfa} |
---|
1413 | Hence, for type ©& const©, there is no pointer assignment, so ©&rc = &x© is disallowed, and \emph{the address value cannot be the null pointer unless an arbitrary pointer is coerced\index{coercion} into the reference}: |
---|
1414 | \begin{cfa} |
---|
1415 | int & const cr = *0; §\C{// where 0 is the int * zero}§ |
---|
1416 | \end{cfa} |
---|
1417 | Note, constant reference-types do not prevent \Index{addressing errors} because of explicit storage-management: |
---|
1418 | \begin{cfa} |
---|
1419 | int & const cr = *malloc(); |
---|
1420 | cr = 5; |
---|
1421 | free( &cr ); |
---|
1422 | cr = 7; §\C{// unsound pointer dereference}§ |
---|
1423 | \end{cfa} |
---|
1424 | |
---|
1425 | The position of the ©const© qualifier \emph{after} the pointer/reference qualifier causes confuse for C programmers. |
---|
1426 | The ©const© qualifier cannot be moved before the pointer/reference qualifier for C style-declarations; |
---|
1427 | \CFA-style declarations (see \VRef{s:Declarations}) attempt to address this issue: |
---|
1428 | \begin{quote2} |
---|
1429 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1430 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1431 | \begin{cfa} |
---|
1432 | ®const® * ®const® * const int ccp; |
---|
1433 | ®const® & ®const® & const int ccr; |
---|
1434 | \end{cfa} |
---|
1435 | & |
---|
1436 | \begin{cfa} |
---|
1437 | const int * ®const® * ®const® ccp; |
---|
1438 | |
---|
1439 | \end{cfa} |
---|
1440 | \end{tabular} |
---|
1441 | \end{quote2} |
---|
1442 | where the \CFA declaration is read left-to-right. |
---|
1443 | |
---|
1444 | Finally, like pointers, references are usable and composable with other type operators and generators. |
---|
1445 | \begin{cfa} |
---|
1446 | int w, x, y, z, & ar[3] = { x, y, z }; §\C{// initialize array of references}§ |
---|
1447 | &ar[1] = &w; §\C{// change reference array element}§ |
---|
1448 | typeof( ar[1] ) p; §\C{// (gcc) is int, i.e., the type of referenced object}§ |
---|
1449 | typeof( &ar[1] ) q; §\C{// (gcc) is int \&, i.e., the type of reference}§ |
---|
1450 | sizeof( ar[1] ) == sizeof( int ); §\C{// is true, i.e., the size of referenced object}§ |
---|
1451 | sizeof( &ar[1] ) == sizeof( int *) §\C{// is true, i.e., the size of a reference}§ |
---|
1452 | \end{cfa} |
---|
1453 | |
---|
1454 | In contrast to \CFA reference types, \Index*[C++]{\CC{}}'s reference types are all ©const© references, preventing changes to the reference address, so only value assignment is possible, which eliminates half of the \Index{address duality}. |
---|
1455 | Also, \CC does not allow \Index{array}s\index{array!reference} of reference\footnote{ |
---|
1456 | The reason for disallowing arrays of reference is unknown, but possibly comes from references being ethereal (like a textual macro), and hence, replaceable by the referant object.} |
---|
1457 | \Index*{Java}'s reference types to objects (all Java objects are on the heap) are like C pointers, which always manipulate the address, and there is no (bit-wise) object assignment, so objects are explicitly cloned by shallow or deep copying, which eliminates half of the address duality. |
---|
1458 | |
---|
1459 | |
---|
1460 | \subsection{Initialization} |
---|
1461 | |
---|
1462 | \Index{Initialization} is different than \Index{assignment} because initialization occurs on the empty (uninitialized) storage on an object, while assignment occurs on possibly initialized storage of an object. |
---|
1463 | There are three initialization contexts in \CFA: declaration initialization, argument/parameter binding, return/temporary binding. |
---|
1464 | Because the object being initialized has no value, there is only one meaningful semantics with respect to address duality: it must mean address as there is no pointed-to value. |
---|
1465 | In contrast, the left-hand side of assignment has an address that has a duality. |
---|
1466 | Therefore, for pointer/reference initialization, the initializing value must be an address not a value. |
---|
1467 | \begin{cfa} |
---|
1468 | int * p = &x; §\C{// assign address of x}§ |
---|
1469 | ®int * p = x;® §\C{// assign value of x}§ |
---|
1470 | int & r = x; §\C{// must have address of x}§ |
---|
1471 | \end{cfa} |
---|
1472 | Like the previous example with C pointer-arithmetic, it is unlikely assigning the value of ©x© into a pointer is meaningful (again, a warning is usually given). |
---|
1473 | Therefore, for safety, this context requires an address, so it is superfluous to require explicitly taking the address of the initialization object, even though the type is incorrect. |
---|
1474 | Note, this is strictly a convenience and safety feature for a programmer. |
---|
1475 | Hence, \CFA allows ©r© to be assigned ©x© because it infers a reference for ©x©, by implicitly inserting a address-of operator, ©&©, and it is an error to put an ©&© because the types no longer match due to the implicit dereference. |
---|
1476 | Unfortunately, C allows ©p© to be assigned with ©&x© (address) or ©x© (value), but most compilers warn about the latter assignment as being potentially incorrect. |
---|
1477 | Similarly, when a reference type is used for a parameter/return type, the call-site argument does not require a reference operator for the same reason. |
---|
1478 | \begin{cfa} |
---|
1479 | int & f( int & r ); §\C{// reference parameter and return}§ |
---|
1480 | z = f( x ) + f( y ); §\C{// reference operator added, temporaries needed for call results}§ |
---|
1481 | \end{cfa} |
---|
1482 | Within routine ©f©, it is possible to change the argument by changing the corresponding parameter, and parameter ©r© can be locally reassigned within ©f©. |
---|
1483 | Since operator routine ©?+?© takes its arguments by value, the references returned from ©f© are used to initialize compiler generated temporaries with value semantics that copy from the references. |
---|
1484 | \begin{cfa} |
---|
1485 | int temp1 = f( x ), temp2 = f( y ); |
---|
1486 | z = temp1 + temp2; |
---|
1487 | \end{cfa} |
---|
1488 | This \Index{implicit referencing} is crucial for reducing the syntactic burden for programmers when using references; |
---|
1489 | otherwise references have the same syntactic burden as pointers in these contexts. |
---|
1490 | |
---|
1491 | When a pointer/reference parameter has a ©const© value (immutable), it is possible to pass literals and expressions. |
---|
1492 | \begin{cfa} |
---|
1493 | void f( ®const® int & cr ); |
---|
1494 | void g( ®const® int * cp ); |
---|
1495 | f( 3 ); g( ®&®3 ); |
---|
1496 | f( x + y ); g( ®&®(x + y) ); |
---|
1497 | \end{cfa} |
---|
1498 | Here, the compiler passes the address to the literal 3 or the temporary for the expression ©x + y©, knowing the argument cannot be changed through the parameter. |
---|
1499 | The ©&© before the constant/expression for the pointer-type parameter (©g©) is a \CFA extension necessary to type match and is a common requirement before a variable in C (\eg ©scanf©). |
---|
1500 | Importantly, ©&3© may not be equal to ©&3©, where the references occur across calls because the temporaries maybe different on each call. |
---|
1501 | |
---|
1502 | \CFA \emph{extends} this semantics to a mutable pointer/reference parameter, and the compiler implicitly creates the necessary temporary (copying the argument), which is subsequently pointed-to by the reference parameter and can be changed.\footnote{ |
---|
1503 | If whole program analysis is possible, and shows the parameter is not assigned, \ie it is ©const©, the temporary is unnecessary.} |
---|
1504 | \begin{cfa} |
---|
1505 | void f( int & r ); |
---|
1506 | void g( int * p ); |
---|
1507 | f( 3 ); g( ®&®3 ); §\C{// compiler implicit generates temporaries}§ |
---|
1508 | f( x + y ); g( ®&®(x + y) ); §\C{// compiler implicit generates temporaries}§ |
---|
1509 | \end{cfa} |
---|
1510 | Essentially, there is an implicit \Index{rvalue} to \Index{lvalue} conversion in this case.\footnote{ |
---|
1511 | This conversion attempts to address the \newterm{const hell} problem, when the innocent addition of a ©const© qualifier causes a cascade of type failures, requiring an unknown number of additional ©const© qualifiers, until it is discovered a ©const© qualifier cannot be added and all the ©const© qualifiers must be removed.} |
---|
1512 | The implicit conversion allows seamless calls to any routine without having to explicitly name/copy the literal/expression to allow the call. |
---|
1513 | |
---|
1514 | %\CFA attempts to handle pointers and references in a uniform, symmetric manner. |
---|
1515 | Finally, C handles \Index{routine object}s in an inconsistent way. |
---|
1516 | A routine object is both a pointer and a reference (\Index{particle and wave}). |
---|
1517 | \begin{cfa} |
---|
1518 | void f( int i ); |
---|
1519 | void (*fp)( int ); §\C{// routine pointer}§ |
---|
1520 | fp = f; §\C{// reference initialization}§ |
---|
1521 | fp = &f; §\C{// pointer initialization}§ |
---|
1522 | fp = *f; §\C{// reference initialization}§ |
---|
1523 | fp(3); §\C{// reference invocation}§ |
---|
1524 | (*fp)(3); §\C{// pointer invocation}§ |
---|
1525 | \end{cfa} |
---|
1526 | While C's treatment of routine objects has similarity to inferring a reference type in initialization contexts, the examples are assignment not initialization, and all possible forms of assignment are possible (©f©, ©&f©, ©*f©) without regard for type. |
---|
1527 | Instead, a routine object should be referenced by a ©const© reference: |
---|
1528 | \begin{cfa} |
---|
1529 | ®const® void (®&® fr)( int ) = f; §\C{// routine reference}§ |
---|
1530 | fr = ... §\C{// error, cannot change code}§ |
---|
1531 | &fr = ...; §\C{// changing routine reference}§ |
---|
1532 | fr( 3 ); §\C{// reference call to f}§ |
---|
1533 | (*fr)(3); §\C{// error, incorrect type}§ |
---|
1534 | \end{cfa} |
---|
1535 | because the value of the routine object is a routine literal, \ie the routine code is normally immutable during execution.\footnote{ |
---|
1536 | Dynamic code rewriting is possible but only in special circumstances.} |
---|
1537 | \CFA allows this additional use of references for routine objects in an attempt to give a more consistent meaning for them. |
---|
1538 | |
---|
1539 | |
---|
1540 | \subsection{Address-of Semantics} |
---|
1541 | |
---|
1542 | In C, ©&E© is an rvalue for any expression ©E©. |
---|
1543 | \CFA extends the ©&© (address-of) operator as follows: |
---|
1544 | \begin{itemize} |
---|
1545 | \item |
---|
1546 | if ©R© is an \Index{rvalue} of type ©T &$_1$...&$_r$© where $r \ge 1$ references (©&© symbols) than ©&R© has type ©T ®*®&$_{\color{red}2}$...&$_{\color{red}r}$©, \ie ©T© pointer with $r-1$ references (©&© symbols). |
---|
1547 | |
---|
1548 | \item |
---|
1549 | if ©L© is an \Index{lvalue} of type ©T &$_1$...&$_l$© where $l \ge 0$ references (©&© symbols) then ©&L© has type ©T ®*®&$_{\color{red}1}$...&$_{\color{red}l}$©, \ie ©T© pointer with $l$ references (©&© symbols). |
---|
1550 | \end{itemize} |
---|
1551 | The following example shows the first rule applied to different \Index{rvalue} contexts: |
---|
1552 | \begin{cfa} |
---|
1553 | int x, * px, ** ppx, *** pppx, **** ppppx; |
---|
1554 | int & rx = x, && rrx = rx, &&& rrrx = rrx ; |
---|
1555 | x = rrrx; // rrrx is an lvalue with type int &&& (equivalent to x) |
---|
1556 | px = &rrrx; // starting from rrrx, &rrrx is an rvalue with type int *&&& (&x) |
---|
1557 | ppx = &&rrrx; // starting from &rrrx, &&rrrx is an rvalue with type int **&& (&rx) |
---|
1558 | pppx = &&&rrrx; // starting from &&rrrx, &&&rrrx is an rvalue with type int ***& (&rrx) |
---|
1559 | ppppx = &&&&rrrx; // starting from &&&rrrx, &&&&rrrx is an rvalue with type int **** (&rrrx) |
---|
1560 | \end{cfa} |
---|
1561 | The following example shows the second rule applied to different \Index{lvalue} contexts: |
---|
1562 | \begin{cfa} |
---|
1563 | int x, * px, ** ppx, *** pppx; |
---|
1564 | int & rx = x, && rrx = rx, &&& rrrx = rrx ; |
---|
1565 | rrrx = 2; // rrrx is an lvalue with type int &&& (equivalent to x) |
---|
1566 | &rrrx = px; // starting from rrrx, &rrrx is an rvalue with type int *&&& (rx) |
---|
1567 | &&rrrx = ppx; // starting from &rrrx, &&rrrx is an rvalue with type int **&& (rrx) |
---|
1568 | &&&rrrx = pppx; // starting from &&rrrx, &&&rrrx is an rvalue with type int ***& (rrrx) |
---|
1569 | \end{cfa} |
---|
1570 | |
---|
1571 | |
---|
1572 | \subsection{Conversions} |
---|
1573 | |
---|
1574 | C provides a basic implicit conversion to simplify variable usage: |
---|
1575 | \begin{enumerate} |
---|
1576 | \setcounter{enumi}{-1} |
---|
1577 | \item |
---|
1578 | lvalue to rvalue conversion: ©cv T© converts to ©T©, which allows implicit variable dereferencing. |
---|
1579 | \begin{cfa} |
---|
1580 | int x; |
---|
1581 | x + 1; // lvalue variable (int) converts to rvalue for expression |
---|
1582 | \end{cfa} |
---|
1583 | An rvalue has no type qualifiers (©cv©), so the lvalue qualifiers are dropped. |
---|
1584 | \end{enumerate} |
---|
1585 | \CFA provides three new implicit conversion for reference types to simplify reference usage. |
---|
1586 | \begin{enumerate} |
---|
1587 | \item |
---|
1588 | reference to rvalue conversion: ©cv T &© converts to ©T©, which allows implicit reference dereferencing. |
---|
1589 | \begin{cfa} |
---|
1590 | int x, &r = x, f( int p ); |
---|
1591 | x = ®r® + f( ®r® ); // lvalue reference converts to rvalue |
---|
1592 | \end{cfa} |
---|
1593 | An rvalue has no type qualifiers (©cv©), so the reference qualifiers are dropped. |
---|
1594 | |
---|
1595 | \item |
---|
1596 | lvalue to reference conversion: \lstinline[deletekeywords=lvalue]$lvalue-type cv1 T$ converts to ©cv2 T &©, which allows implicitly converting variables to references. |
---|
1597 | \begin{cfa} |
---|
1598 | int x, &r = ®x®, f( int & p ); // lvalue variable (int) convert to reference (int &) |
---|
1599 | f( ®x® ); // lvalue variable (int) convert to reference (int &) |
---|
1600 | \end{cfa} |
---|
1601 | Conversion can restrict a type, where ©cv1© $\le$ ©cv2©, \eg passing an ©int© to a ©const volatile int &©, which has low cost. |
---|
1602 | Conversion can expand a type, where ©cv1© $>$ ©cv2©, \eg passing a ©const volatile int© to an ©int &©, which has high cost (\Index{warning}); |
---|
1603 | furthermore, if ©cv1© has ©const© but not ©cv2©, a temporary variable is created to preserve the immutable lvalue. |
---|
1604 | |
---|
1605 | \item |
---|
1606 | rvalue to reference conversion: ©T© converts to ©cv T &©, which allows binding references to temporaries. |
---|
1607 | \begin{cfa} |
---|
1608 | int x, & f( int & p ); |
---|
1609 | f( ®x + 3® ); // rvalue parameter (int) implicitly converts to lvalue temporary reference (int &) |
---|
1610 | ®&f®(...) = &x; // rvalue result (int &) implicitly converts to lvalue temporary reference (int &) |
---|
1611 | \end{cfa} |
---|
1612 | In both case, modifications to the temporary are inaccessible (\Index{warning}). |
---|
1613 | Conversion expands the temporary-type with ©cv©, which is low cost since the temporary is inaccessible. |
---|
1614 | \end{enumerate} |
---|
1615 | |
---|
1616 | |
---|
1617 | \begin{comment} |
---|
1618 | From: Richard Bilson <rcbilson@gmail.com> |
---|
1619 | Date: Wed, 13 Jul 2016 01:58:58 +0000 |
---|
1620 | Subject: Re: pointers / references |
---|
1621 | To: "Peter A. Buhr" <pabuhr@plg2.cs.uwaterloo.ca> |
---|
1622 | |
---|
1623 | As a general comment I would say that I found the section confusing, as you move back and forth |
---|
1624 | between various real and imagined programming languages. If it were me I would rewrite into two |
---|
1625 | subsections, one that specifies precisely the syntax and semantics of reference variables and |
---|
1626 | another that provides the rationale. |
---|
1627 | |
---|
1628 | I don't see any obvious problems with the syntax or semantics so far as I understand them. It's not |
---|
1629 | obvious that the description you're giving is complete, but I'm sure you'll find the special cases |
---|
1630 | as you do the implementation. |
---|
1631 | |
---|
1632 | My big gripes are mostly that you're not being as precise as you need to be in your terminology, and |
---|
1633 | that you say a few things that aren't actually true even though I generally know what you mean. |
---|
1634 | |
---|
1635 | 20 C provides a pointer type; CFA adds a reference type. Both types contain an address, which is normally a |
---|
1636 | 21 location in memory. |
---|
1637 | |
---|
1638 | An address is not a location in memory; an address refers to a location in memory. Furthermore it |
---|
1639 | seems weird to me to say that a type "contains" an address; rather, objects of that type do. |
---|
1640 | |
---|
1641 | 21 Special addresses are used to denote certain states or access co-processor memory. By |
---|
1642 | 22 convention, no variable is placed at address 0, so addresses like 0, 1, 2, 3 are often used to denote no-value |
---|
1643 | 23 or other special states. |
---|
1644 | |
---|
1645 | This isn't standard C at all. There has to be one null pointer representation, but it doesn't have |
---|
1646 | to be a literal zero representation and there doesn't have to be more than one such representation. |
---|
1647 | |
---|
1648 | 23 Often dereferencing a special state causes a memory fault, so checking is necessary |
---|
1649 | 24 during execution. |
---|
1650 | |
---|
1651 | I don't see the connection between the two clauses here. I feel like if a bad pointer will not cause |
---|
1652 | a memory fault then I need to do more checking, not less. |
---|
1653 | |
---|
1654 | 24 If the programming language assigns addresses, a program's execution is sound, \ie all |
---|
1655 | 25 addresses are to valid memory locations. |
---|
1656 | |
---|
1657 | You haven't said what it means to "assign" an address, but if I use my intuitive understanding of |
---|
1658 | the term I don't see how this can be true unless you're assuming automatic storage management. |
---|
1659 | |
---|
1660 | 1 Program variables are implicit pointers to memory locations generated by the compiler and automatically |
---|
1661 | 2 dereferenced, as in: |
---|
1662 | |
---|
1663 | There is no reason why a variable needs to have a location in memory, and indeed in a typical |
---|
1664 | program many variables will not. In standard terminology an object identifier refers to data in the |
---|
1665 | execution environment, but not necessarily in memory. |
---|
1666 | |
---|
1667 | 13 A pointer/reference is a generalization of a variable name, \ie a mutable address that can point to more |
---|
1668 | 14 than one memory location during its lifetime. |
---|
1669 | |
---|
1670 | I feel like you're off the reservation here. In my world there are objects of pointer type, which |
---|
1671 | seem to be what you're describing here, but also pointer values, which can be stored in an object of |
---|
1672 | pointer type but don't necessarily have to be. For example, how would you describe the value denoted |
---|
1673 | by "&main" in a C program? I would call it a (function) pointer, but that doesn't satisfy your |
---|
1674 | definition. |
---|
1675 | |
---|
1676 | 16 not occupy storage as the literal is embedded directly into instructions.) Hence, a pointer occupies memory |
---|
1677 | 17 to store its current address, and the pointer's value is loaded by dereferencing, \eg: |
---|
1678 | |
---|
1679 | As with my general objection regarding your definition of variables, there is no reason why a |
---|
1680 | pointer variable (object of pointer type) needs to occupy memory. |
---|
1681 | |
---|
1682 | 21 p2 = p1 + x; // compiler infers *p2 = *p1 + x; |
---|
1683 | |
---|
1684 | What language are we in now? |
---|
1685 | |
---|
1686 | 24 pointer usage. However, in C, the following cases are ambiguous, especially with pointer arithmetic: |
---|
1687 | 25 p1 = p2; // p1 = p2 or *p1 = *p2 |
---|
1688 | |
---|
1689 | This isn't ambiguous. it's defined to be the first option. |
---|
1690 | |
---|
1691 | 26 p1 = p1 + 1; // p1 = p1 + 1 or *p1 = *p1 + 1 |
---|
1692 | |
---|
1693 | Again, this statement is not ambiguous. |
---|
1694 | |
---|
1695 | 13 example. Hence, a reference behaves like the variable name for the current variable it is pointing-to. The |
---|
1696 | 14 simplest way to understand a reference is to imagine the compiler inserting a dereference operator before |
---|
1697 | 15 the reference variable for each reference qualifier in a declaration, \eg: |
---|
1698 | |
---|
1699 | It's hard for me to understand who the audience for this part is. I think a practical programmer is |
---|
1700 | likely to be satisfied with "a reference behaves like the variable name for the current variable it |
---|
1701 | is pointing-to," maybe with some examples. Your "simplest way" doesn't strike me as simpler than |
---|
1702 | that. It feels like you're trying to provide a more precise definition for the semantics of |
---|
1703 | references, but it isn't actually precise enough to be a formal specification. If you want to |
---|
1704 | express the semantics of references using rewrite rules that's a great way to do it, but lay the |
---|
1705 | rules out clearly, and when you're showing an example of rewriting keep your |
---|
1706 | references/pointers/values separate (right now, you use \eg "r3" to mean a reference, a pointer, |
---|
1707 | and a value). |
---|
1708 | |
---|
1709 | 24 Cancellation works to arbitrary depth, and pointer and reference values are interchangeable because both |
---|
1710 | 25 contain addresses. |
---|
1711 | |
---|
1712 | Except they're not interchangeable, because they have different and incompatible types. |
---|
1713 | |
---|
1714 | 40 Interestingly, C++ deals with the address duality by making the pointed-to value the default, and prevent- |
---|
1715 | 41 ing changes to the reference address, which eliminates half of the duality. Java deals with the address duality |
---|
1716 | 42 by making address assignment the default and requiring field assignment (direct or indirect via methods), |
---|
1717 | 43 \ie there is no builtin bit-wise or method-wise assignment, which eliminates half of the duality. |
---|
1718 | |
---|
1719 | I can follow this but I think that's mostly because I already understand what you're trying to |
---|
1720 | say. I don't think I've ever heard the term "method-wise assignment" and I don't see you defining |
---|
1721 | it. Furthermore Java does have value assignment of basic (non-class) types, so your summary here |
---|
1722 | feels incomplete. (If it were me I'd drop this paragraph rather than try to save it.) |
---|
1723 | |
---|
1724 | 11 Hence, for type & const, there is no pointer assignment, so &rc = &x is disallowed, and the address value |
---|
1725 | 12 cannot be 0 unless an arbitrary pointer is assigned to the reference. |
---|
1726 | |
---|
1727 | Given the pains you've taken to motivate every little bit of the semantics up until now, this last |
---|
1728 | clause ("the address value cannot be 0") comes out of the blue. It seems like you could have |
---|
1729 | perfectly reasonable semantics that allowed the initialization of null references. |
---|
1730 | |
---|
1731 | 12 In effect, the compiler is managing the |
---|
1732 | 13 addresses for type & const not the programmer, and by a programming discipline of only using references |
---|
1733 | 14 with references, address errors can be prevented. |
---|
1734 | |
---|
1735 | Again, is this assuming automatic storage management? |
---|
1736 | |
---|
1737 | 18 rary binding. For reference initialization (like pointer), the initializing value must be an address (lvalue) not |
---|
1738 | 19 a value (rvalue). |
---|
1739 | |
---|
1740 | This sentence appears to suggest that an address and an lvalue are the same thing. |
---|
1741 | |
---|
1742 | 20 int * p = &x; // both &x and x are possible interpretations |
---|
1743 | |
---|
1744 | Are you saying that we should be considering "x" as a possible interpretation of the initializer |
---|
1745 | "&x"? It seems to me that this expression has only one legitimate interpretation in context. |
---|
1746 | |
---|
1747 | 21 int & r = x; // x unlikely interpretation, because of auto-dereferencing |
---|
1748 | |
---|
1749 | You mean, we can initialize a reference using an integer value? Surely we would need some sort of |
---|
1750 | cast to induce that interpretation, no? |
---|
1751 | |
---|
1752 | 22 Hence, the compiler implicitly inserts a reference operator, &, before the initialization expression. |
---|
1753 | |
---|
1754 | But then the expression would have pointer type, which wouldn't be compatible with the type of r. |
---|
1755 | |
---|
1756 | 22 Similarly, |
---|
1757 | 23 when a reference is used for a parameter/return type, the call-site argument does not require a reference |
---|
1758 | 24 operator. |
---|
1759 | |
---|
1760 | Furthermore, it would not be correct to use a reference operator. |
---|
1761 | |
---|
1762 | 45 The implicit conversion allows |
---|
1763 | 1 seamless calls to any routine without having to explicitly name/copy the literal/expression to allow the call. |
---|
1764 | 2 While C' attempts to handle pointers and references in a uniform, symmetric manner, C handles routine |
---|
1765 | 3 variables in an inconsistent way: a routine variable is both a pointer and a reference (particle and wave). |
---|
1766 | |
---|
1767 | After all this talk of how expressions can have both pointer and value interpretations, you're |
---|
1768 | disparaging C because it has expressions that have both pointer and value interpretations? |
---|
1769 | |
---|
1770 | On Sat, Jul 9, 2016 at 4:18 PM Peter A. Buhr <pabuhr@plg.uwaterloo.ca> wrote: |
---|
1771 | > Aaron discovered a few places where "&"s are missing and where there are too many "&", which are |
---|
1772 | > corrected in the attached updated. None of the text has changed, if you have started reading |
---|
1773 | > already. |
---|
1774 | \end{comment} |
---|
1775 | |
---|
1776 | |
---|
1777 | \section{Routine Definition} |
---|
1778 | |
---|
1779 | \CFA also supports a new syntax for routine definition, as well as \Celeven and K\&R routine syntax. |
---|
1780 | The point of the new syntax is to allow returning multiple values from a routine~\cite{Galletly96,CLU}, \eg: |
---|
1781 | \begin{cfa} |
---|
1782 | ®[ int o1, int o2, char o3 ]® f( int i1, char i2, char i3 ) { |
---|
1783 | §\emph{routine body}§ |
---|
1784 | } |
---|
1785 | \end{cfa} |
---|
1786 | where routine ©f© has three output (return values) and three input parameters. |
---|
1787 | 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. |
---|
1788 | |
---|
1789 | In detail, the brackets, ©[]©, enclose the result type, where each return value is named and that name is a local variable of the particular return type.\footnote{ |
---|
1790 | \Index*{Michael Tiemann}, with help from \Index*{Doug Lea}, provided named return values in g++, circa 1989.} |
---|
1791 | The value of each local return variable is automatically returned at routine termination. |
---|
1792 | Declaration qualifiers can only appear at the start of a routine definition, \eg: |
---|
1793 | \begin{cfa} |
---|
1794 | ®extern® [ int x ] g( int y ) {§\,§} |
---|
1795 | \end{cfa} |
---|
1796 | Lastly, if there are no output parameters or input parameters, the brackets and/or parentheses must still be specified; |
---|
1797 | 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: |
---|
1798 | \begin{cfa} |
---|
1799 | [§\,§] g(); §\C{// no input or output parameters}§ |
---|
1800 | [ void ] g( void ); §\C{// no input or output parameters}§ |
---|
1801 | \end{cfa} |
---|
1802 | |
---|
1803 | Routine f is called as follows: |
---|
1804 | \begin{cfa} |
---|
1805 | [ i, j, ch ] = f( 3, 'a', ch ); |
---|
1806 | \end{cfa} |
---|
1807 | The list of return values from f and the grouping on the left-hand side of the assignment is called a \newterm{return list} and discussed in Section 12. |
---|
1808 | |
---|
1809 | \CFA style declarations cannot be used to declare parameters for K\&R style routine definitions because of the following ambiguity: |
---|
1810 | \begin{cfa} |
---|
1811 | int (*f(x))[ 5 ] int x; {} |
---|
1812 | \end{cfa} |
---|
1813 | The string ``©int (*f(x))[ 5 ]©'' declares a K\&R style routine of type returning a pointer to an array of 5 integers, while the string ``©[ 5 ] int x©'' declares a \CFA style parameter x of type array of 5 integers. |
---|
1814 | Since the strings overlap starting with the open bracket, ©[©, there is an ambiguous interpretation for the string. |
---|
1815 | As well, \CFA-style declarations cannot be used to declare parameters for C-style routine-definitions because of the following ambiguity: |
---|
1816 | \begin{cfa} |
---|
1817 | typedef int foo; |
---|
1818 | int f( int (* foo) ); §\C{// foo is redefined as a parameter name}§ |
---|
1819 | \end{cfa} |
---|
1820 | The string ``©int (* foo)©'' declares a C-style named-parameter of type pointer to an integer (the parenthesis are superfluous), while the same string declares a \CFA style unnamed parameter of type routine returning integer with unnamed parameter of type pointer to foo. |
---|
1821 | The redefinition of a type name in a parameter list is the only context in C where the character ©*© can appear to the left of a type name, and \CFA relies on all type qualifier characters appearing to the right of the type name. |
---|
1822 | 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. |
---|
1823 | |
---|
1824 | C-style declarations can be used to declare parameters for \CFA style routine definitions, \eg: |
---|
1825 | \begin{cfa} |
---|
1826 | [ int ] f( * int, int * ); §\C{// returns an integer, accepts 2 pointers to integers}§ |
---|
1827 | [ * int, int * ] f( int ); §\C{// returns 2 pointers to integers, accepts an integer}§ |
---|
1828 | \end{cfa} |
---|
1829 | 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: |
---|
1830 | \begin{cfa} |
---|
1831 | #define ptoa( n, d ) int (*n)[ d ] |
---|
1832 | int f( ptoa( p, 5 ) ) ... §\C{// expands to int f( int (*p)[ 5 ] )}§ |
---|
1833 | [ int ] f( ptoa( p, 5 ) ) ... §\C{// expands to [ int ] f( int (*p)[ 5 ] )}§ |
---|
1834 | \end{cfa} |
---|
1835 | Again, programmers are highly encouraged to use one declaration form or the other, rather than mixing the forms. |
---|
1836 | |
---|
1837 | |
---|
1838 | \subsection{Named Return Values} |
---|
1839 | |
---|
1840 | \Index{Named return values} handle the case where it is necessary to define a local variable whose value is then returned in a ©return© statement, as in: |
---|
1841 | \begin{cfa} |
---|
1842 | int f() { |
---|
1843 | int x; |
---|
1844 | ... x = 0; ... x = y; ... |
---|
1845 | return x; |
---|
1846 | } |
---|
1847 | \end{cfa} |
---|
1848 | Because the value in the return variable is automatically returned when a \CFA routine terminates, the ©return© statement \emph{does not} contain an expression, as in: |
---|
1849 | \newline |
---|
1850 | \begin{minipage}{\linewidth} |
---|
1851 | \begin{cfa} |
---|
1852 | ®[ int x, int y ]® f() { |
---|
1853 | int z; |
---|
1854 | ... x = 0; ... y = z; ... |
---|
1855 | ®return;® §\C{// implicitly return x, y}§ |
---|
1856 | } |
---|
1857 | \end{cfa} |
---|
1858 | \end{minipage} |
---|
1859 | \newline |
---|
1860 | When the return is encountered, the current values of ©x© and ©y© are returned to the calling routine. |
---|
1861 | As well, ``falling off the end'' of a routine without a ©return© statement is permitted, as in: |
---|
1862 | \begin{cfa} |
---|
1863 | [ int x, int y ] f() { |
---|
1864 | ... |
---|
1865 | } §\C{// implicitly return x, y}§ |
---|
1866 | \end{cfa} |
---|
1867 | In this case, the current values of ©x© and ©y© are returned to the calling routine just as if a ©return© had been encountered. |
---|
1868 | |
---|
1869 | Named return values may be used in conjunction with named parameter values; |
---|
1870 | specifically, a return and parameter can have the same name. |
---|
1871 | \begin{cfa} |
---|
1872 | [ int x, int y ] f( int, x, int y ) { |
---|
1873 | ... |
---|
1874 | } §\C{// implicitly return x, y}§ |
---|
1875 | \end{cfa} |
---|
1876 | This notation allows the compiler to eliminate temporary variables in nested routine calls. |
---|
1877 | \begin{cfa} |
---|
1878 | [ int x, int y ] f( int, x, int y ); §\C{// prototype declaration}§ |
---|
1879 | int a, b; |
---|
1880 | [a, b] = f( f( f( a, b ) ) ); |
---|
1881 | \end{cfa} |
---|
1882 | While the compiler normally ignores parameters names in prototype declarations, here they are used to eliminate temporary return-values by inferring that the results of each call are the inputs of the next call, and ultimately, the left-hand side of the assignment. |
---|
1883 | Hence, even without the body of routine ©f© (separate compilation), it is possible to perform a global optimization across routine calls. |
---|
1884 | The compiler warns about naming inconsistencies between routine prototype and definition in this case, and behaviour is \Index{undefined} if the programmer is inconsistent. |
---|
1885 | |
---|
1886 | |
---|
1887 | \subsection{Routine Prototype} |
---|
1888 | |
---|
1889 | The syntax of the new routine prototype declaration follows directly from the new routine definition syntax; |
---|
1890 | as well, parameter names are optional, \eg: |
---|
1891 | \begin{cfa} |
---|
1892 | [ int x ] f (); §\C{// returning int with no parameters}§ |
---|
1893 | [ * int ] g (int y); §\C{// returning pointer to int with int parameter}§ |
---|
1894 | [ ] h ( int, char ); §\C{// returning no result with int and char parameters}§ |
---|
1895 | [ * int, int ] j ( int ); §\C{// returning pointer to int and int, with int parameter}§ |
---|
1896 | \end{cfa} |
---|
1897 | This syntax allows a prototype declaration to be created by cutting and pasting source text from the routine definition header (or vice versa). |
---|
1898 | It is possible to declare multiple routine-prototypes in a single declaration, but the entire type specification is distributed across \emph{all} routine names in the declaration list (see~\VRef{s:Declarations}), \eg: |
---|
1899 | \begin{quote2} |
---|
1900 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
1901 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{C}} \\ |
---|
1902 | \begin{cfa} |
---|
1903 | [ int ] f( int ), g; |
---|
1904 | \end{cfa} |
---|
1905 | & |
---|
1906 | \begin{cfa} |
---|
1907 | int f( int ), g( int ); |
---|
1908 | \end{cfa} |
---|
1909 | \end{tabular} |
---|
1910 | \end{quote2} |
---|
1911 | Declaration qualifiers can only appear at the start of a \CFA routine declaration,\footref{StorageClassSpecifier} \eg: |
---|
1912 | \begin{cfa} |
---|
1913 | extern [ int ] f ( int ); |
---|
1914 | static [ int ] g ( int ); |
---|
1915 | \end{cfa} |
---|
1916 | |
---|
1917 | |
---|
1918 | \section{Routine Pointers} |
---|
1919 | |
---|
1920 | The syntax for pointers to \CFA routines specifies the pointer name on the right, \eg: |
---|
1921 | \begin{cfa} |
---|
1922 | * [ int x ] () fp; §\C{// pointer to routine returning int with no parameters}§ |
---|
1923 | * [ * int ] (int y) gp; §\C{// pointer to routine returning pointer to int with int parameter}§ |
---|
1924 | * [ ] (int,char) hp; §\C{// pointer to routine returning no result with int and char parameters}§ |
---|
1925 | * [ * int,int ] ( int ) jp; §\C{// pointer to routine returning pointer to int and int, with int parameter}§ |
---|
1926 | \end{cfa} |
---|
1927 | While parameter names are optional, \emph{a routine name cannot be specified}; |
---|
1928 | for example, the following is incorrect: |
---|
1929 | \begin{cfa} |
---|
1930 | * [ int x ] f () fp; §\C{// routine name "f" is not allowed}§ |
---|
1931 | \end{cfa} |
---|
1932 | |
---|
1933 | |
---|
1934 | \section{Named and Default Arguments} |
---|
1935 | |
---|
1936 | Named\index{named arguments}\index{arguments!named} and default\index{default arguments}\index{arguments!default} arguments~\cite{Hardgrave76}\footnote{ |
---|
1937 | 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.} |
---|
1938 | are two mechanisms to simplify routine call. |
---|
1939 | Both mechanisms are discussed with respect to \CFA. |
---|
1940 | \begin{description} |
---|
1941 | \item[Named (or Keyword) Arguments:] |
---|
1942 | provide the ability to specify an argument to a routine call using the parameter name rather than the position of the parameter. |
---|
1943 | For example, given the routine: |
---|
1944 | \begin{cfa} |
---|
1945 | void p( int x, int y, int z ) {...} |
---|
1946 | \end{cfa} |
---|
1947 | a positional call is: |
---|
1948 | \begin{cfa} |
---|
1949 | p( 4, 7, 3 ); |
---|
1950 | \end{cfa} |
---|
1951 | whereas a named (keyword) call may be: |
---|
1952 | \begin{cfa} |
---|
1953 | p( z : 3, x : 4, y : 7 ); §\C{// rewrite $\Rightarrow$ p( 4, 7, 3 )}§ |
---|
1954 | \end{cfa} |
---|
1955 | Here the order of the arguments is unimportant, and the names of the parameters are used to associate argument values with the corresponding parameters. |
---|
1956 | The compiler rewrites a named call into a positional call. |
---|
1957 | The advantages of named parameters are: |
---|
1958 | \begin{itemize} |
---|
1959 | \item |
---|
1960 | Remembering the names of the parameters may be easier than the order in the routine definition. |
---|
1961 | \item |
---|
1962 | Parameter names provide documentation at the call site (assuming the names are descriptive). |
---|
1963 | \item |
---|
1964 | Changes can be made to the order or number of parameters without affecting the call (although the call must still be recompiled). |
---|
1965 | \end{itemize} |
---|
1966 | |
---|
1967 | 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. |
---|
1968 | For example, the following routine prototypes and definition are all valid. |
---|
1969 | \begin{cfa} |
---|
1970 | void p( int, int, int ); §\C{// equivalent prototypes}§ |
---|
1971 | void p( int x, int y, int z ); |
---|
1972 | void p( int y, int x, int z ); |
---|
1973 | void p( int z, int y, int x ); |
---|
1974 | void p( int q, int r, int s ) {} §\C{// match with this definition}§ |
---|
1975 | \end{cfa} |
---|
1976 | Forcing matching parameter names in routine prototypes with corresponding routine definitions is possible, but goes against a strong tradition in C programming. |
---|
1977 | Alternatively, prototype definitions can be eliminated by using a two-pass compilation, and implicitly creating header files for exports. |
---|
1978 | The former is easy to do, while the latter is more complex. |
---|
1979 | |
---|
1980 | Furthermore, named arguments do not work well in a \CFA-style programming-languages because they potentially introduces a new criteria for type matching. |
---|
1981 | For example, it is technically possible to disambiguate between these two overloaded definitions of ©f© based on named arguments at the call site: |
---|
1982 | \begin{cfa} |
---|
1983 | int f( int i, int j ); |
---|
1984 | int f( int x, double y ); |
---|
1985 | |
---|
1986 | f( j : 3, i : 4 ); §\C{// 1st f}§ |
---|
1987 | f( x : 7, y : 8.1 ); §\C{// 2nd f}§ |
---|
1988 | f( 4, 5 ); §\C{// ambiguous call}§ |
---|
1989 | \end{cfa} |
---|
1990 | However, named arguments compound routine resolution in conjunction with conversions: |
---|
1991 | \begin{cfa} |
---|
1992 | f( i : 3, 5.7 ); §\C{// ambiguous call ?}§ |
---|
1993 | \end{cfa} |
---|
1994 | Depending on the cost associated with named arguments, this call could be resolvable or ambiguous. |
---|
1995 | Adding named argument into the routine resolution algorithm does not seem worth the complexity. |
---|
1996 | Therefore, \CFA does \emph{not} attempt to support named arguments. |
---|
1997 | |
---|
1998 | \item[Default Arguments] |
---|
1999 | provide the ability to associate a default value with a parameter so it can be optionally specified in the argument list. |
---|
2000 | For example, given the routine: |
---|
2001 | \begin{cfa} |
---|
2002 | void p( int x = 1, int y = 2, int z = 3 ) {...} |
---|
2003 | \end{cfa} |
---|
2004 | the allowable positional calls are: |
---|
2005 | \begin{cfa} |
---|
2006 | p(); §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§ |
---|
2007 | p( 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§ |
---|
2008 | p( 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§ |
---|
2009 | p( 4, 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 4 )}§ |
---|
2010 | // empty arguments |
---|
2011 | p( , 4, 4 ); §\C{// rewrite $\Rightarrow$ p( 1, 4, 4 )}§ |
---|
2012 | p( 4, , 4 ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 4 )}§ |
---|
2013 | p( 4, 4, ); §\C{// rewrite $\Rightarrow$ p( 4, 4, 3 )}§ |
---|
2014 | p( 4, , ); §\C{// rewrite $\Rightarrow$ p( 4, 2, 3 )}§ |
---|
2015 | p( , 4, ); §\C{// rewrite $\Rightarrow$ p( 1, 4, 3 )}§ |
---|
2016 | p( , , 4 ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 4 )}§ |
---|
2017 | p( , , ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 3 )}§ |
---|
2018 | \end{cfa} |
---|
2019 | Here the missing arguments are inserted from the default values in the parameter list. |
---|
2020 | The compiler rewrites missing default values into explicit positional arguments. |
---|
2021 | The advantages of default values are: |
---|
2022 | \begin{itemize} |
---|
2023 | \item |
---|
2024 | 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. |
---|
2025 | For many of these kinds of routines, there are standard or default settings that work for the majority of computations. |
---|
2026 | 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. |
---|
2027 | \item |
---|
2028 | When a routine's interface is augmented with new parameters, it extends the interface providing generalizability\footnote{ |
---|
2029 | ``It should be possible for the implementor of an abstraction to increase its generality. |
---|
2030 | So long as the modified abstraction is a generalization of the original, existing uses of the abstraction will not require change. |
---|
2031 | 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. |
---|
2032 | 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}} |
---|
2033 | (somewhat like the generalization provided by inheritance for classes). |
---|
2034 | That is, all existing calls are still valid, although the call must still be recompiled. |
---|
2035 | \end{itemize} |
---|
2036 | The only disadvantage of default arguments is that unintentional omission of an argument may not result in a compiler-time error. |
---|
2037 | Instead, a default value is used, which may not be the programmer's intent. |
---|
2038 | |
---|
2039 | Default values may only appear in a prototype versus definition context: |
---|
2040 | \begin{cfa} |
---|
2041 | void p( int x, int y = 2, int z = 3 ); §\C{// prototype: allowed}§ |
---|
2042 | void p( int, int = 2, int = 3 ); §\C{// prototype: allowed}§ |
---|
2043 | void p( int x, int y = 2, int z = 3 ) {} §\C{// definition: not allowed}§ |
---|
2044 | \end{cfa} |
---|
2045 | The reason for this restriction is to allow separate compilation. |
---|
2046 | Multiple prototypes with different default values is an error. |
---|
2047 | \end{description} |
---|
2048 | |
---|
2049 | Ellipse (``...'') arguments present problems when used with default arguments. |
---|
2050 | The conflict occurs because both named and ellipse arguments must appear after positional arguments, giving two possibilities: |
---|
2051 | \begin{cfa} |
---|
2052 | p( /* positional */, ... , /* named */ ); |
---|
2053 | p( /* positional */, /* named */, ... ); |
---|
2054 | \end{cfa} |
---|
2055 | While it is possible to implement both approaches, the first possibly is more complex than the second, \eg: |
---|
2056 | \begin{cfa} |
---|
2057 | p( int x, int y, int z, ... ); |
---|
2058 | p( 1, 4, 5, 6, z : 3, y : 2 ); §\C{// assume p( /* positional */, ... , /* named */ );}§ |
---|
2059 | p( 1, z : 3, y : 2, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, ... );}§ |
---|
2060 | \end{cfa} |
---|
2061 | 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. |
---|
2062 | Hence, this approach seems significantly more difficult, and hence, confusing and error prone. |
---|
2063 | In the second call, the named arguments separate the positional and ellipse arguments, making it trivial to read the call. |
---|
2064 | |
---|
2065 | The problem is exacerbated with default arguments, \eg: |
---|
2066 | \begin{cfa} |
---|
2067 | void p( int x, int y = 2, int z = 3... ); |
---|
2068 | p( 1, 4, 5, 6, z : 3 ); §\C{// assume p( /* positional */, ... , /* named */ );}§ |
---|
2069 | p( 1, z : 3, 4, 5, 6 ); §\C{// assume p( /* positional */, /* named */, ... );}§ |
---|
2070 | \end{cfa} |
---|
2071 | The first call is an error because arguments 4 and 5 are actually positional not ellipse arguments; |
---|
2072 | therefore, argument 5 subsequently conflicts with the named argument z : 3. |
---|
2073 | 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. |
---|
2074 | For these reasons, \CFA requires named arguments before ellipse arguments. |
---|
2075 | 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. |
---|
2076 | |
---|
2077 | Default arguments and overloading (see Section 24) are complementary. |
---|
2078 | While in theory default arguments can be simulated with overloading, as in: |
---|
2079 | \begin{quote2} |
---|
2080 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
2081 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{default arguments}} & \multicolumn{1}{c}{\textbf{overloading}} \\ |
---|
2082 | \begin{cfa} |
---|
2083 | void p( int x, int y = 2, int z = 3 ) {...} |
---|
2084 | |
---|
2085 | |
---|
2086 | \end{cfa} |
---|
2087 | & |
---|
2088 | \begin{cfa} |
---|
2089 | void p( int x, int y, int z ) {...} |
---|
2090 | void p( int x ) { p( x, 2, 3 ); } |
---|
2091 | void p( int x, int y ) { p( x, y, 3 ); } |
---|
2092 | \end{cfa} |
---|
2093 | \end{tabular} |
---|
2094 | \end{quote2} |
---|
2095 | the number of required overloaded routines is linear in the number of default values, which is unacceptable growth. |
---|
2096 | In general, overloading should only be used over default arguments if the body of the routine is significantly different. |
---|
2097 | Furthermore, overloading cannot handle accessing default arguments in the middle of a positional list, via a missing argument, such as: |
---|
2098 | \begin{cfa} |
---|
2099 | p( 1, /* default */, 5 ); §\C{// rewrite $\Rightarrow$ p( 1, 2, 5 )}§ |
---|
2100 | \end{cfa} |
---|
2101 | |
---|
2102 | Given the \CFA restrictions above, both named and default arguments are backwards compatible. |
---|
2103 | \Index*[C++]{\CC{}} only supports default arguments; |
---|
2104 | \Index*{Ada} supports both named and default arguments. |
---|
2105 | |
---|
2106 | |
---|
2107 | \section{Unnamed Structure Fields} |
---|
2108 | |
---|
2109 | C requires each field of a structure to have a name, except for a bit field associated with a basic type, \eg: |
---|
2110 | \begin{cfa} |
---|
2111 | struct { |
---|
2112 | int f1; §\C{// named field}§ |
---|
2113 | int f2 : 4; §\C{// named field with bit field size}§ |
---|
2114 | int : 3; §\C{// unnamed field for basic type with bit field size}§ |
---|
2115 | int ; §\C{// disallowed, unnamed field}§ |
---|
2116 | int *; §\C{// disallowed, unnamed field}§ |
---|
2117 | int (*)( int ); §\C{// disallowed, unnamed field}§ |
---|
2118 | }; |
---|
2119 | \end{cfa} |
---|
2120 | This requirement is relaxed by making the field name optional for all field declarations; therefore, all the field declarations in the example are allowed. |
---|
2121 | As for unnamed bit fields, an unnamed field is used for padding a structure to a particular size. |
---|
2122 | A list of unnamed fields is also supported, \eg: |
---|
2123 | \begin{cfa} |
---|
2124 | struct { |
---|
2125 | int , , ; §\C{// 3 unnamed fields}§ |
---|
2126 | } |
---|
2127 | \end{cfa} |
---|
2128 | |
---|
2129 | |
---|
2130 | \section{Nesting} |
---|
2131 | |
---|
2132 | Nesting of types and routines is useful for controlling name visibility (\newterm{name hiding}). |
---|
2133 | |
---|
2134 | |
---|
2135 | \subsection{Type Nesting} |
---|
2136 | |
---|
2137 | \CFA allows \Index{type nesting}, and type qualification of the nested types (see \VRef[Figure]{f:TypeNestingQualification}), where as C hoists\index{type hoisting} (refactors) nested types into the enclosing scope and has no type qualification. |
---|
2138 | \begin{figure} |
---|
2139 | \centering |
---|
2140 | \begin{tabular}{@{}l@{\hspace{3em}}l|l@{}} |
---|
2141 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{C Type Nesting}} & \multicolumn{1}{c}{\textbf{C Implicit Hoisting}} & \multicolumn{1}{|c}{\textbf{\CFA}} \\ |
---|
2142 | \hline |
---|
2143 | \begin{cfa} |
---|
2144 | struct S { |
---|
2145 | enum C { R, G, B }; |
---|
2146 | struct T { |
---|
2147 | union U { int i, j; }; |
---|
2148 | enum C c; |
---|
2149 | short int i, j; |
---|
2150 | }; |
---|
2151 | struct T t; |
---|
2152 | } s; |
---|
2153 | |
---|
2154 | int fred() { |
---|
2155 | s.t.c = R; |
---|
2156 | struct T t = { R, 1, 2 }; |
---|
2157 | enum C c; |
---|
2158 | union U u; |
---|
2159 | } |
---|
2160 | \end{cfa} |
---|
2161 | & |
---|
2162 | \begin{cfa} |
---|
2163 | enum C { R, G, B }; |
---|
2164 | union U { int i, j; }; |
---|
2165 | struct T { |
---|
2166 | enum C c; |
---|
2167 | short int i, j; |
---|
2168 | }; |
---|
2169 | struct S { |
---|
2170 | struct T t; |
---|
2171 | } s; |
---|
2172 | |
---|
2173 | |
---|
2174 | |
---|
2175 | |
---|
2176 | |
---|
2177 | |
---|
2178 | |
---|
2179 | \end{cfa} |
---|
2180 | & |
---|
2181 | \begin{cfa} |
---|
2182 | struct S { |
---|
2183 | enum C { R, G, B }; |
---|
2184 | struct T { |
---|
2185 | union U { int i, j; }; |
---|
2186 | enum C c; |
---|
2187 | short int i, j; |
---|
2188 | }; |
---|
2189 | struct T t; |
---|
2190 | } s; |
---|
2191 | |
---|
2192 | int fred() { |
---|
2193 | s.t.c = ®S.®R; // type qualification |
---|
2194 | struct ®S.®T t = { ®S.®R, 1, 2 }; |
---|
2195 | enum ®S.®C c; |
---|
2196 | union ®S.T.®U u; |
---|
2197 | } |
---|
2198 | \end{cfa} |
---|
2199 | \end{tabular} |
---|
2200 | \caption{Type Nesting / Qualification} |
---|
2201 | \label{f:TypeNestingQualification} |
---|
2202 | \end{figure} |
---|
2203 | In the left example in C, types ©C©, ©U© and ©T© are implicitly hoisted outside of type ©S© into the containing block scope. |
---|
2204 | In the right example in \CFA, the types are not hoisted and accessed using the field-selection operator ``©.©'' for type qualification, as does \Index*{Java}, rather than the \CC type-selection operator ``©::©''. |
---|
2205 | |
---|
2206 | |
---|
2207 | \subsection{Routine Nesting} |
---|
2208 | |
---|
2209 | 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. |
---|
2210 | For example, the C quick-sort is wrapped into the following polymorphic \CFA routine: |
---|
2211 | \begin{cfa} |
---|
2212 | forall( otype T | { int ?<?( T, T ); } ) |
---|
2213 | void qsort( const T * arr, size_t dimension ); |
---|
2214 | \end{cfa} |
---|
2215 | which can be used to sort in ascending and descending order by locally redefining the less-than operator into greater-than. |
---|
2216 | \begin{cfa} |
---|
2217 | const unsigned int size = 5; |
---|
2218 | int ia[size]; |
---|
2219 | ... §\C{// assign values to array ia}§ |
---|
2220 | qsort( ia, size ); §\C{// sort ascending order using builtin ?<?}§ |
---|
2221 | { |
---|
2222 | ®int ?<?( int x, int y ) { return x > y; }® §\C{// nested routine}§ |
---|
2223 | qsort( ia, size ); §\C{// sort descending order by local redefinition}§ |
---|
2224 | } |
---|
2225 | \end{cfa} |
---|
2226 | |
---|
2227 | Nested routines are not first-class, meaning a nested routine cannot be returned if it has references to variables in its enclosing blocks; |
---|
2228 | the only exception is references to the external block of the translation unit, as these variables persist for the duration of the program. |
---|
2229 | The following program in undefined in \CFA (and Indexc{gcc}) |
---|
2230 | \begin{cfa} |
---|
2231 | [* [int]( int )] foo() { §\C{// int (*foo())( int )}§ |
---|
2232 | int ®i® = 7; |
---|
2233 | int bar( int p ) { |
---|
2234 | ®i® += 1; §\C{// dependent on local variable}§ |
---|
2235 | sout | ®i® | endl; |
---|
2236 | } |
---|
2237 | return bar; §\C{// undefined because of local dependence}§ |
---|
2238 | } |
---|
2239 | int main() { |
---|
2240 | * [int]( int ) fp = foo(); §\C{// int (*fp)( int )}§ |
---|
2241 | sout | fp( 3 ) | endl; |
---|
2242 | } |
---|
2243 | \end{cfa} |
---|
2244 | because |
---|
2245 | |
---|
2246 | Currently, there are no \Index{lambda} expressions, \ie unnamed routines because routine names are very important to properly select the correct routine. |
---|
2247 | |
---|
2248 | |
---|
2249 | \section{Tuples} |
---|
2250 | |
---|
2251 | In C and \CFA, lists of elements appear in several contexts, such as the parameter list for a routine call. |
---|
2252 | (More contexts are added shortly.) |
---|
2253 | A list of such elements is called a \newterm{lexical list}. |
---|
2254 | The general syntax of a lexical list is: |
---|
2255 | \begin{cfa} |
---|
2256 | [ §\emph{exprlist}§ ] |
---|
2257 | \end{cfa} |
---|
2258 | where ©$\emph{exprlist}$© is a list of one or more expressions separated by commas. |
---|
2259 | The brackets, ©[]©, allow differentiating between lexical lists and expressions containing the C comma operator. |
---|
2260 | The following are examples of lexical lists: |
---|
2261 | \begin{cfa} |
---|
2262 | [ x, y, z ] |
---|
2263 | [ 2 ] |
---|
2264 | [ v+w, x*y, 3.14159, f() ] |
---|
2265 | \end{cfa} |
---|
2266 | Tuples are permitted to contain sub-tuples (\ie nesting), such as ©[ [ 14, 21 ], 9 ]©, which is a 2-element tuple whose first element is itself a tuple. |
---|
2267 | Note, a tuple is not a record (structure); |
---|
2268 | a record denotes a single value with substructure, whereas a tuple is multiple values with no substructure (see flattening coercion in Section 12.1). |
---|
2269 | In essence, tuples are largely a compile time phenomenon, having little or no runtime presence. |
---|
2270 | |
---|
2271 | Tuples can be organized into compile-time tuple variables; |
---|
2272 | these variables are of \newterm{tuple type}. |
---|
2273 | Tuple variables and types can be used anywhere lists of conventional variables and types can be used. |
---|
2274 | The general syntax of a tuple type is: |
---|
2275 | \begin{cfa} |
---|
2276 | [ §\emph{typelist}§ ] |
---|
2277 | \end{cfa} |
---|
2278 | where ©$\emph{typelist}$© is a list of one or more legal \CFA or C type specifications separated by commas, which may include other tuple type specifications. |
---|
2279 | Examples of tuple types include: |
---|
2280 | \begin{cfa} |
---|
2281 | [ unsigned int, char ] |
---|
2282 | [ double, double, double ] |
---|
2283 | [ * int, int * ] §\C{// mix of CFA and ANSI}§ |
---|
2284 | [ * [ 5 ] int, * * char, * [ [ int, int ] ] (int, int) ] |
---|
2285 | \end{cfa} |
---|
2286 | Like tuples, tuple types may be nested, such as ©[ [ int, int ], int ]©, which is a 2-element tuple type whose first element is itself a tuple type. |
---|
2287 | |
---|
2288 | Examples of declarations using tuple types are: |
---|
2289 | \begin{cfa} |
---|
2290 | [ int, int ] x; §\C{// 2 element tuple, each element of type int}§ |
---|
2291 | * [ char, char ] y; §\C{// pointer to a 2 element tuple}§ |
---|
2292 | [ [ int, int ] ] z ([ int, int ]); |
---|
2293 | \end{cfa} |
---|
2294 | 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. |
---|
2295 | |
---|
2296 | As mentioned, tuples can appear in contexts requiring a list of value, such as an argument list of a routine call. |
---|
2297 | In unambiguous situations, the tuple brackets may be omitted, \eg a tuple that appears as an argument may have its |
---|
2298 | square brackets omitted for convenience; therefore, the following routine invocations are equivalent: |
---|
2299 | \begin{cfa} |
---|
2300 | f( [ 1, x+2, fred() ] ); |
---|
2301 | f( 1, x+2, fred() ); |
---|
2302 | \end{cfa} |
---|
2303 | 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. |
---|
2304 | For example, the following are all legal: |
---|
2305 | \begin{cfa} |
---|
2306 | [ int, int ] w1; |
---|
2307 | [ int, int, int ] w2; |
---|
2308 | [ void ] f (int, int, int); /* three input parameters of type int */ |
---|
2309 | [ void ] g ([ int, int, int ]); /* 3 element tuple as input */ |
---|
2310 | f( [ 1, 2, 3 ] ); |
---|
2311 | f( w1, 3 ); |
---|
2312 | f( 1, w1 ); |
---|
2313 | f( w2 ); |
---|
2314 | g( [ 1, 2, 3 ] ); |
---|
2315 | g( w1, 3 ); |
---|
2316 | g( 1, w1 ); |
---|
2317 | g( w2 ); |
---|
2318 | \end{cfa} |
---|
2319 | Note, in all cases 3 arguments are supplied even though the syntax may appear to supply less than 3. As mentioned, a |
---|
2320 | tuple does not have structure like a record; a tuple is simply converted into a list of components. |
---|
2321 | \begin{rationale} |
---|
2322 | The present implementation of \CFA does not support nested routine calls when the inner routine returns multiple values; \ie a statement such as ©g( f() )© is not supported. |
---|
2323 | Using a temporary variable to store the results of the inner routine and then passing this variable to the outer routine works, however. |
---|
2324 | \end{rationale} |
---|
2325 | |
---|
2326 | A tuple can contain a C comma expression, provided the expression containing the comma operator is enclosed in parentheses. |
---|
2327 | For instance, the following tuples are equivalent: |
---|
2328 | \begin{cfa} |
---|
2329 | [ 1, 3, 5 ] |
---|
2330 | [ 1, (2, 3), 5 ] |
---|
2331 | \end{cfa} |
---|
2332 | The second element of the second tuple is the expression (2, 3), which yields the result 3. |
---|
2333 | This requirement is the same as for comma expressions in argument lists. |
---|
2334 | |
---|
2335 | Type qualifiers, \ie const and volatile, may modify a tuple type. |
---|
2336 | The meaning is the same as for a type qualifier modifying an aggregate type [Int99, x 6.5.2.3(7),x 6.7.3(11)], \ie the qualifier is distributed across all of the types in the tuple, \eg: |
---|
2337 | \begin{cfa} |
---|
2338 | const volatile [ int, float, const int ] x; |
---|
2339 | \end{cfa} |
---|
2340 | is equivalent to: |
---|
2341 | \begin{cfa} |
---|
2342 | [ const volatile int, const volatile float, const volatile int ] x; |
---|
2343 | \end{cfa} |
---|
2344 | Declaration qualifiers can only appear at the start of a \CFA tuple declaration4, \eg: |
---|
2345 | \begin{cfa} |
---|
2346 | extern [ int, int ] w1; |
---|
2347 | static [ int, int, int ] w2; |
---|
2348 | \end{cfa} |
---|
2349 | \begin{rationale} |
---|
2350 | Unfortunately, C's syntax for subscripts precluded treating them as tuples. |
---|
2351 | The C subscript list has the form ©[i][j]...© and not ©[i, j, ...]©. |
---|
2352 | Therefore, there is no syntactic way for a routine returning multiple values to specify the different subscript values, \eg ©f[g()]© always means a single subscript value because there is only one set of brackets. |
---|
2353 | Fixing this requires a major change to C because the syntactic form ©M[i, j, k]© already has a particular meaning: ©i, j, k© is a comma expression. |
---|
2354 | \end{rationale} |
---|
2355 | |
---|
2356 | |
---|
2357 | \subsection{Tuple Coercions} |
---|
2358 | |
---|
2359 | There are four coercions that can be performed on tuples and tuple variables: closing, opening, flattening and structuring. |
---|
2360 | In addition, the coercion of dereferencing can be performed on a tuple variable to yield its value(s), as for other variables. |
---|
2361 | 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: |
---|
2362 | \begin{cfa} |
---|
2363 | [ int, int, int, int ] w; |
---|
2364 | w = [ 1, 2, 3, 4 ]; |
---|
2365 | \end{cfa} |
---|
2366 | First the right-hand tuple is closed into a tuple value and then the tuple value is assigned. |
---|
2367 | |
---|
2368 | An \newterm{opening coercion} is the opposite of closing; a tuple value is converted into a tuple of values, as in: |
---|
2369 | \begin{cfa} |
---|
2370 | [ a, b, c, d ] = w |
---|
2371 | \end{cfa} |
---|
2372 | ©w© is implicitly opened to yield a tuple of four values, which are then assigned individually. |
---|
2373 | |
---|
2374 | A \newterm{flattening coercion} coerces a nested tuple, \ie a tuple with one or more components, which are themselves tuples, into a flattened tuple, which is a tuple whose components are not tuples, as in: |
---|
2375 | \begin{cfa} |
---|
2376 | [ a, b, c, d ] = [ 1, [ 2, 3 ], 4 ]; |
---|
2377 | \end{cfa} |
---|
2378 | First the right-hand tuple is flattened and then the values are assigned individually. |
---|
2379 | Flattening is also performed on tuple types. |
---|
2380 | For example, the type ©[ int, [ int, int ], int ]© can be coerced, using flattening, into the type ©[ int, int, int, int ]©. |
---|
2381 | |
---|
2382 | A \newterm{structuring coercion} is the opposite of flattening; |
---|
2383 | a tuple is structured into a more complex nested tuple. |
---|
2384 | For example, structuring the tuple ©[ 1, 2, 3, 4 ]© into the tuple ©[ 1, [ 2, 3 ], 4 ]© or the tuple type ©[ int, int, int, int ]© into the tuple type ©[ int, [ int, int ], int ]©. |
---|
2385 | In the following example, the last assignment illustrates all the tuple coercions: |
---|
2386 | \begin{cfa} |
---|
2387 | [ int, int, int, int ] w = [ 1, 2, 3, 4 ]; |
---|
2388 | int x = 5; |
---|
2389 | [ x, w ] = [ w, x ]; §\C{// all four tuple coercions}§ |
---|
2390 | \end{cfa} |
---|
2391 | Starting on the right-hand tuple in the last assignment statement, w is opened, producing a tuple of four values; |
---|
2392 | therefore, the right-hand tuple is now the tuple ©[ [ 1, 2, 3, 4 ], 5 ]©. |
---|
2393 | This tuple is then flattened, yielding ©[ 1, 2, 3, 4, 5 ]©, which is structured into ©[ 1, [ 2, 3, 4, 5 ] ]© to match the tuple type of the left-hand side. |
---|
2394 | The tuple ©[ 2, 3, 4, 5 ]© is then closed to create a tuple value. |
---|
2395 | Finally, ©x© is assigned ©1© and ©w© is assigned the tuple value using multiple assignment (see Section 14). |
---|
2396 | \begin{rationale} |
---|
2397 | A possible additional language extension is to use the structuring coercion for tuples to initialize a complex record with a tuple. |
---|
2398 | \end{rationale} |
---|
2399 | |
---|
2400 | |
---|
2401 | \section{Mass Assignment} |
---|
2402 | |
---|
2403 | \CFA permits assignment to several variables at once using mass assignment~\cite{CLU}. |
---|
2404 | Mass assignment has the following form: |
---|
2405 | \begin{cfa} |
---|
2406 | [ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = §\emph{expr}§; |
---|
2407 | \end{cfa} |
---|
2408 | \index{lvalue} |
---|
2409 | The left-hand side is a tuple of \emph{lvalues}, which is a list of expressions each yielding an address, \ie any data object that can appear on the left-hand side of a conventional assignment statement. |
---|
2410 | ©$\emph{expr}$© is any standard arithmetic expression. |
---|
2411 | Clearly, the types of the entities being assigned must be type compatible with the value of the expression. |
---|
2412 | |
---|
2413 | Mass assignment has parallel semantics, \eg the statement: |
---|
2414 | \begin{cfa} |
---|
2415 | [ x, y, z ] = 1.5; |
---|
2416 | \end{cfa} |
---|
2417 | is equivalent to: |
---|
2418 | \begin{cfa} |
---|
2419 | x = 1.5; y = 1.5; z = 1.5; |
---|
2420 | \end{cfa} |
---|
2421 | This semantics is not the same as the following in C: |
---|
2422 | \begin{cfa} |
---|
2423 | x = y = z = 1.5; |
---|
2424 | \end{cfa} |
---|
2425 | as conversions between intermediate assignments may lose information. |
---|
2426 | A more complex example is: |
---|
2427 | \begin{cfa} |
---|
2428 | [ i, y[i], z ] = a + b; |
---|
2429 | \end{cfa} |
---|
2430 | which is equivalent to: |
---|
2431 | \begin{cfa} |
---|
2432 | t = a + b; |
---|
2433 | a1 = &i; a2 = &y[i]; a3 = &z; |
---|
2434 | *a1 = t; *a2 = t; *a3 = t; |
---|
2435 | \end{cfa} |
---|
2436 | The temporary ©t© is necessary to store the value of the expression to eliminate conversion issues. |
---|
2437 | The temporaries for the addresses are needed so that locations on the left-hand side do not change as the values are assigned. |
---|
2438 | In this case, ©y[i]© uses the previous value of ©i© and not the new value set at the beginning of the mass assignment. |
---|
2439 | |
---|
2440 | |
---|
2441 | \section{Multiple Assignment} |
---|
2442 | |
---|
2443 | \CFA also supports the assignment of several values at once, known as multiple assignment~\cite{CLU,Galletly96}. |
---|
2444 | Multiple assignment has the following form: |
---|
2445 | \begin{cfa} |
---|
2446 | [ §\emph{lvalue}§, ... , §\emph{lvalue}§ ] = [ §\emph{expr}§, ... , §\emph{expr}§ ]; |
---|
2447 | \end{cfa} |
---|
2448 | \index{lvalue} |
---|
2449 | The left-hand side is a tuple of \emph{lvalues}, and the right-hand side is a tuple of \emph{expr}s. |
---|
2450 | Each \emph{expr} appearing on the right-hand side of a multiple assignment statement is assigned to the corresponding \emph{lvalues} on the left-hand side of the statement using parallel semantics for each assignment. |
---|
2451 | An example of multiple assignment is: |
---|
2452 | \begin{cfa} |
---|
2453 | [ x, y, z ] = [ 1, 2, 3 ]; |
---|
2454 | \end{cfa} |
---|
2455 | Here, the values ©1©, ©2© and ©3© are assigned, respectively, to the variables ©x©, ©y© and ©z©. |
---|
2456 | A more complex example is: |
---|
2457 | \begin{cfa} |
---|
2458 | [ i, y[ i ], z ] = [ 1, i, a + b ]; |
---|
2459 | \end{cfa} |
---|
2460 | Here, the values ©1©, ©i© and ©a + b© are assigned to the variables ©i©, ©y[i]© and ©z©, respectively. |
---|
2461 | Note, the parallel semantics of |
---|
2462 | multiple assignment ensures: |
---|
2463 | \begin{cfa} |
---|
2464 | [ x, y ] = [ y, x ]; |
---|
2465 | \end{cfa} |
---|
2466 | correctly interchanges (swaps) the values stored in ©x© and ©y©. |
---|
2467 | The following cases are errors: |
---|
2468 | \begin{cfa} |
---|
2469 | [ a, b, c ] = [ 1, 2, 3, 4 ]; |
---|
2470 | [ a, b, c ] = [ 1, 2 ]; |
---|
2471 | \end{cfa} |
---|
2472 | because the number of entities in the left-hand tuple is unequal with the right-hand tuple. |
---|
2473 | |
---|
2474 | 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; |
---|
2475 | both these examples produce indeterminate results: |
---|
2476 | \begin{cfa} |
---|
2477 | f( x++, x++ ); §\C{// C routine call with side effects in arguments}§ |
---|
2478 | [ v1, v2 ] = [ x++, x++ ]; §\C{// side effects in righthand side of multiple assignment}§ |
---|
2479 | \end{cfa} |
---|
2480 | |
---|
2481 | |
---|
2482 | \section{Cascade Assignment} |
---|
2483 | |
---|
2484 | As in C, \CFA mass and multiple assignments can be cascaded, producing cascade assignment. |
---|
2485 | Cascade assignment has the following form: |
---|
2486 | \begin{cfa} |
---|
2487 | §\emph{tuple}§ = §\emph{tuple}§ = ... = §\emph{tuple}§; |
---|
2488 | \end{cfa} |
---|
2489 | and it has the same parallel semantics as for mass and multiple assignment. |
---|
2490 | Some examples of cascade assignment are: |
---|
2491 | \begin{cfa} |
---|
2492 | x1 = y1 = x2 = y2 = 0; |
---|
2493 | [ x1, y1 ] = [ x2, y2 ] = [ x3, y3 ]; |
---|
2494 | [ x1, y1 ] = [ x2, y2 ] = 0; |
---|
2495 | [ x1, y1 ] = z = 0; |
---|
2496 | \end{cfa} |
---|
2497 | As in C, the rightmost assignment is performed first, \ie assignment parses right to left. |
---|
2498 | |
---|
2499 | |
---|
2500 | \section{Field Tuples} |
---|
2501 | |
---|
2502 | Tuples may be used to select multiple fields of a record by field name. |
---|
2503 | Its general form is: |
---|
2504 | \begin{cfa} |
---|
2505 | §\emph{expr}§ . [ §\emph{fieldlist}§ ] |
---|
2506 | §\emph{expr}§ -> [ §\emph{fieldlist}§ ] |
---|
2507 | \end{cfa} |
---|
2508 | \emph{expr} is any expression yielding a value of type record, \eg ©struct©, ©union©. |
---|
2509 | Each element of \emph{ fieldlist} is an element of the record specified by \emph{expr}. |
---|
2510 | A record-field tuple may be used anywhere a tuple can be used. An example of the use of a record-field tuple is |
---|
2511 | the following: |
---|
2512 | \begin{cfa} |
---|
2513 | struct s { |
---|
2514 | int f1, f2; |
---|
2515 | char f3; |
---|
2516 | double f4; |
---|
2517 | } v; |
---|
2518 | v.[ f3, f1, f2 ] = ['x', 11, 17 ]; §\C{// equivalent to v.f3 = 'x', v.f1 = 11, v.f2 = 17}§ |
---|
2519 | f( v.[ f3, f1, f2 ] ); §\C{// equivalent to f( v.f3, v.f1, v.f2 )}§ |
---|
2520 | \end{cfa} |
---|
2521 | Note, the fields appearing in a record-field tuple may be specified in any order; |
---|
2522 | also, it is unnecessary to specify all the fields of a struct in a multiple record-field tuple. |
---|
2523 | |
---|
2524 | If a field of a ©struct© is itself another ©struct©, multiple fields of this subrecord can be specified using a nested record-field tuple, as in the following example: |
---|
2525 | \begin{cfa} |
---|
2526 | struct inner { |
---|
2527 | int f2, f3; |
---|
2528 | }; |
---|
2529 | struct outer { |
---|
2530 | int f1; |
---|
2531 | struct inner i; |
---|
2532 | double f4; |
---|
2533 | } o; |
---|
2534 | |
---|
2535 | o.[ f1, i.[ f2, f3 ], f4 ] = [ 11, 12, 13, 3.14159 ]; |
---|
2536 | \end{cfa} |
---|
2537 | |
---|
2538 | |
---|
2539 | \section{I/O Library} |
---|
2540 | \label{s:IOLibrary} |
---|
2541 | \index{input/output library} |
---|
2542 | |
---|
2543 | The goal of \CFA I/O is to simplify the common cases\index{I/O!common case}, while fully supporting polymorphism and user defined types in a consistent way. |
---|
2544 | The approach combines ideas from \CC and Python. |
---|
2545 | The \CFA header file for the I/O library is \Indexc{fstream}. |
---|
2546 | |
---|
2547 | The common case is printing out a sequence of variables separated by whitespace. |
---|
2548 | \begin{quote2} |
---|
2549 | \begin{tabular}{@{}l@{\hspace{3em}}l@{}} |
---|
2550 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CFA}} & \multicolumn{1}{c}{\textbf{\CC}} \\ |
---|
2551 | \begin{cfa} |
---|
2552 | int x = 1, y = 2, z = 3; |
---|
2553 | sout | x ®|® y ®|® z | endl; |
---|
2554 | \end{cfa} |
---|
2555 | & |
---|
2556 | \begin{cfa} |
---|
2557 | |
---|
2558 | cout << x ®<< " "® << y ®<< " "® << z << endl; |
---|
2559 | \end{cfa} |
---|
2560 | \\ |
---|
2561 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2562 | 1® ®2® ®3 |
---|
2563 | \end{cfa} |
---|
2564 | & |
---|
2565 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2566 | 1 2 3 |
---|
2567 | \end{cfa} |
---|
2568 | \end{tabular} |
---|
2569 | \end{quote2} |
---|
2570 | The \CFA form has half the characters of the \CC form, and is similar to \Index*{Python} I/O with respect to implicit separators. |
---|
2571 | Similar simplification occurs for \Index{tuple} I/O, which prints all tuple values separated by ``\lstinline[showspaces=true]@, @''. |
---|
2572 | \begin{cfa} |
---|
2573 | [int, [ int, int ] ] t1 = [ 1, [ 2, 3 ] ], t2 = [ 4, [ 5, 6 ] ]; |
---|
2574 | sout | t1 | t2 | endl; §\C{// print tuples}§ |
---|
2575 | \end{cfa} |
---|
2576 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2577 | 1®, ®2®, ®3 4®, ®5®, ®6 |
---|
2578 | \end{cfa} |
---|
2579 | Finally, \CFA uses the logical-or operator for I/O as it is the lowest-priority overloadable operator, other than assignment. |
---|
2580 | Therefore, fewer output expressions require parenthesis. |
---|
2581 | \begin{quote2} |
---|
2582 | \begin{tabular}{@{}ll@{}} |
---|
2583 | \textbf{\CFA:} |
---|
2584 | & |
---|
2585 | \begin{cfa} |
---|
2586 | sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl; |
---|
2587 | \end{cfa} |
---|
2588 | \\ |
---|
2589 | \textbf{\CC:} |
---|
2590 | & |
---|
2591 | \begin{cfa} |
---|
2592 | cout << x * 3 << y + 1 << ®(®z << 2®)® << ®(®x == y®)® << (x | y) << (x || y) << (x > z ? 1 : 2) << endl; |
---|
2593 | \end{cfa} |
---|
2594 | \\ |
---|
2595 | & |
---|
2596 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2597 | 3 3 12 0 3 1 2 |
---|
2598 | \end{cfa} |
---|
2599 | \end{tabular} |
---|
2600 | \end{quote2} |
---|
2601 | There is a weak similarity between the \CFA logical-or operator and the Shell pipe-operator for moving data, where data flows in the correct direction for input but the opposite direction for output. |
---|
2602 | |
---|
2603 | |
---|
2604 | \subsection{Implicit Separator} |
---|
2605 | |
---|
2606 | The \Index{implicit separator}\index{I/O!separator} character (space/blank) is a separator not a terminator. |
---|
2607 | The rules for implicitly adding the separator are: |
---|
2608 | \begin{enumerate} |
---|
2609 | \item |
---|
2610 | A separator does not appear at the start or end of a line. |
---|
2611 | \begin{cfa}[belowskip=0pt] |
---|
2612 | sout | 1 | 2 | 3 | endl; |
---|
2613 | \end{cfa} |
---|
2614 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2615 | 1 2 3 |
---|
2616 | \end{cfa} |
---|
2617 | |
---|
2618 | \item |
---|
2619 | A separator does not appear before or after a character literal or variable. |
---|
2620 | \begin{cfa} |
---|
2621 | sout | '1' | '2' | '3' | endl; |
---|
2622 | 123 |
---|
2623 | \end{cfa} |
---|
2624 | |
---|
2625 | \item |
---|
2626 | A separator does not appear before or after a null (empty) C string. |
---|
2627 | \begin{cfa} |
---|
2628 | sout | 1 | "" | 2 | "" | 3 | endl; |
---|
2629 | 123 |
---|
2630 | \end{cfa} |
---|
2631 | which is a local mechanism to disable insertion of the separator character. |
---|
2632 | |
---|
2633 | \item |
---|
2634 | A separator does not appear before a C string starting with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[mathescape=off,basicstyle=\tt]@([{=$£¥¡¿«@ |
---|
2635 | %$ |
---|
2636 | \begin{cfa}[mathescape=off] |
---|
2637 | sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x £" | 6 | "x ¥" |
---|
2638 | | 7 | "x ¡" | 8 | "x ¿" | 9 | "x «" | 10 | endl; |
---|
2639 | \end{cfa} |
---|
2640 | %$ |
---|
2641 | \begin{cfa}[mathescape=off,basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2642 | x ®(®1 x ®[®2 x ®{®3 x ®=®4 x ®$®5 x ®£®6 x ®¥®7 x ®¡®8 x ®¿®9 x ®«®10 |
---|
2643 | \end{cfa} |
---|
2644 | %$ |
---|
2645 | where \lstinline[basicstyle=\tt]@¡¿@ are inverted opening exclamation and question marks, and \lstinline[basicstyle=\tt]@«@ is an opening citation mark. |
---|
2646 | |
---|
2647 | \item |
---|
2648 | {\lstset{language=CFA,deletedelim=**[is][]{¢}{¢}} |
---|
2649 | A seperator does not appear after a C string ending with the (extended) \Index*{ASCII}\index{ASCII!extended} characters: \lstinline[basicstyle=\tt]@,.;!?)]}%¢»@ |
---|
2650 | \begin{cfa}[belowskip=0pt] |
---|
2651 | sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x" |
---|
2652 | | 7 | "¢ x" | 8 | "» x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl; |
---|
2653 | \end{cfa} |
---|
2654 | \begin{cfa}[basicstyle=\tt,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2655 | 1®,® x 2®.® x 3®;® x 4®!® x 5®?® x 6®%® x 7§\color{red}\textcent§ x 8®»® x 9®)® x 10®]® x 11®}® x |
---|
2656 | \end{cfa}}% |
---|
2657 | where \lstinline[basicstyle=\tt]@»@ is a closing citation mark. |
---|
2658 | |
---|
2659 | \item |
---|
2660 | A seperator does not appear before or after a C string begining/ending with the \Index*{ASCII} quote or whitespace characters: \lstinline[basicstyle=\tt,showspaces=true]@`'": \t\v\f\r\n@ |
---|
2661 | \begin{cfa}[belowskip=0pt] |
---|
2662 | sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl; |
---|
2663 | \end{cfa} |
---|
2664 | \begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt] |
---|
2665 | x®`®1®`®x§\color{red}\texttt{'}§2§\color{red}\texttt{'}§x§\color{red}\texttt{"}§3§\color{red}\texttt{"}§x®:®4®:®x® ®5® ®x® ®6® ®x |
---|
2666 | \end{cfa} |
---|
2667 | |
---|
2668 | \item |
---|
2669 | If a space is desired before or after one of the special string start/end characters, simply insert a space. |
---|
2670 | \begin{cfa}[belowskip=0pt] |
---|
2671 | sout | "x (§\color{red}\texttt{\textvisiblespace}§" | 1 | "§\color{red}\texttt{\textvisiblespace}§) x" | 2 | "§\color{red}\texttt{\textvisiblespace}§, x" | 3 | "§\color{red}\texttt{\textvisiblespace}§:x:§\color{red}\texttt{\textvisiblespace}§" | 4 | endl; |
---|
2672 | \end{cfa} |
---|
2673 | \begin{cfa}[basicstyle=\tt,showspaces=true,showtabs=true,aboveskip=0pt,belowskip=0pt] |
---|
2674 | x (® ®1® ®) x 2® ®, x 3® ®:x:® ®4 |
---|
2675 | \end{cfa} |
---|
2676 | \end{enumerate} |
---|
2677 | |
---|
2678 | |
---|
2679 | \subsection{Manipulator} |
---|
2680 | |
---|
2681 | The following \CC-style \Index{manipulator}s and routines control implicit seperation. |
---|
2682 | \begin{enumerate} |
---|
2683 | \item |
---|
2684 | Routines \Indexc{sepSet}\index{manipulator!sepSet@©sepSet©} and \Indexc{sep}\index{manipulator!sep@©sep©}/\Indexc{sepGet}\index{manipulator!sepGet@©sepGet©} set and get the separator string. |
---|
2685 | The separator string can be at most 16 characters including the ©'\0'© string terminator (15 printable characters). |
---|
2686 | \begin{cfa}[mathescape=off,belowskip=0pt] |
---|
2687 | sepSet( sout, ", $" ); §\C{// set separator from " " to ", \$"}§ |
---|
2688 | sout | 1 | 2 | 3 | " \"" | ®sep® | "\"" | endl; |
---|
2689 | \end{cfa} |
---|
2690 | %$ |
---|
2691 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt] |
---|
2692 | 1®, $®2®, $®3 ®", $"® |
---|
2693 | \end{cfa} |
---|
2694 | %$ |
---|
2695 | \begin{cfa}[belowskip=0pt] |
---|
2696 | sepSet( sout, " " ); §\C{// reset separator to " "}§ |
---|
2697 | sout | 1 | 2 | 3 | " \"" | ®sepGet( sout )® | "\"" | endl; |
---|
2698 | \end{cfa} |
---|
2699 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2700 | 1® ®2® ®3 ®" "® |
---|
2701 | \end{cfa} |
---|
2702 | ©sepGet© can be used to store a separator and then restore it: |
---|
2703 | \begin{cfa}[belowskip=0pt] |
---|
2704 | char store[®sepSize®]; §\C{// sepSize is the maximum separator size}§ |
---|
2705 | strcpy( store, sepGet( sout ) ); §\C{// copy current separator}§ |
---|
2706 | sepSet( sout, "_" ); §\C{// change separator to underscore}§ |
---|
2707 | sout | 1 | 2 | 3 | endl; |
---|
2708 | \end{cfa} |
---|
2709 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2710 | 1®_®2®_®3 |
---|
2711 | \end{cfa} |
---|
2712 | \begin{cfa}[belowskip=0pt] |
---|
2713 | sepSet( sout, store ); §\C{// change separator back to original}§ |
---|
2714 | sout | 1 | 2 | 3 | endl; |
---|
2715 | \end{cfa} |
---|
2716 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2717 | 1® ®2® ®3 |
---|
2718 | \end{cfa} |
---|
2719 | |
---|
2720 | \item |
---|
2721 | Routine \Indexc{sepSetTuple}\index{manipulator!sepSetTuple@©sepSetTuple©} and \Indexc{sepTuple}\index{manipulator!sepTuple@©sepTuple©}/\Indexc{sepGetTuple}\index{manipulator!sepGetTuple@©sepGetTuple©} get and set the tuple separator-string. |
---|
2722 | The tuple separator-string can be at most 16 characters including the ©'\0'© string terminator (15 printable characters). |
---|
2723 | \begin{cfa}[belowskip=0pt] |
---|
2724 | sepSetTuple( sout, " " ); §\C{// set tuple separator from ", " to " "}§ |
---|
2725 | sout | t1 | t2 | " \"" | ®sepTuple® | "\"" | endl; |
---|
2726 | \end{cfa} |
---|
2727 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2728 | 1 2 3 4 5 6 ®" "® |
---|
2729 | \end{cfa} |
---|
2730 | \begin{cfa}[belowskip=0pt] |
---|
2731 | sepSetTuple( sout, ", " ); §\C{// reset tuple separator to ", "}§ |
---|
2732 | sout | t1 | t2 | " \"" | ®sepGetTuple( sout )® | "\"" | endl; |
---|
2733 | \end{cfa} |
---|
2734 | \begin{cfa}[showspaces=true,aboveskip=0pt] |
---|
2735 | 1, 2, 3 4, 5, 6 ®", "® |
---|
2736 | \end{cfa} |
---|
2737 | As for ©sepGet©, ©sepGetTuple© can be use to store a tuple separator and then restore it. |
---|
2738 | |
---|
2739 | \item |
---|
2740 | Manipulators \Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} \emph{globally} toggle printing the separator, \ie the seperator is adjusted with respect to all subsequent printed items. |
---|
2741 | \begin{cfa}[belowskip=0pt] |
---|
2742 | sout | sepDisable | 1 | 2 | 3 | endl; §\C{// globally turn off implicit separator}§ |
---|
2743 | \end{cfa} |
---|
2744 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2745 | 123 |
---|
2746 | \end{cfa} |
---|
2747 | \begin{cfa}[belowskip=0pt] |
---|
2748 | sout | sepEnable | 1 | 2 | 3 | endl; §\C{// globally turn on implicit separator}§ |
---|
2749 | \end{cfa} |
---|
2750 | \begin{cfa}[mathescape=off,showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2751 | 1 2 3 |
---|
2752 | \end{cfa} |
---|
2753 | |
---|
2754 | \item |
---|
2755 | Manipulators \Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} \emph{locally} toggle printing the separator, \ie the seperator is adjusted only with respect to the next printed item. |
---|
2756 | \begin{cfa}[belowskip=0pt] |
---|
2757 | sout | 1 | sepOff | 2 | 3 | endl; §\C{// locally turn off implicit separator}§ |
---|
2758 | \end{cfa} |
---|
2759 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2760 | 12 3 |
---|
2761 | \end{cfa} |
---|
2762 | \begin{cfa}[belowskip=0pt] |
---|
2763 | sout | sepDisable | 1 | sepOn | 2 | 3 | endl; §\C{// locally turn on implicit separator}§ |
---|
2764 | \end{cfa} |
---|
2765 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2766 | 1 23 |
---|
2767 | \end{cfa} |
---|
2768 | The tuple separator also responses to being turned on and off. |
---|
2769 | \begin{cfa}[belowskip=0pt] |
---|
2770 | sout | t1 | sepOff | t2 | endl; §\C{// locally turn on/off implicit separator}§ |
---|
2771 | \end{cfa} |
---|
2772 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2773 | 1, 2, 34, 5, 6 |
---|
2774 | \end{cfa} |
---|
2775 | ©sepOn© \emph{cannot} be used to start/end a line with a separator because separators do not appear at the start/end of a line; |
---|
2776 | use ©sep© to accomplish this functionality. |
---|
2777 | \begin{cfa}[belowskip=0pt] |
---|
2778 | sout | sepOn | 1 | 2 | 3 | sepOn | endl ; §\C{// sepOn does nothing at start/end of line}§ |
---|
2779 | \end{cfa} |
---|
2780 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2781 | 1 2 3 |
---|
2782 | \end{cfa} |
---|
2783 | \begin{cfa}[belowskip=0pt] |
---|
2784 | sout | sep | 1 | 2 | 3 | sep | endl ; §\C{// use sep to print separator at start/end of line}§ |
---|
2785 | \end{cfa} |
---|
2786 | \begin{cfa}[showspaces=true,aboveskip=0pt,belowskip=0pt] |
---|
2787 | ® ®1 2 3® ® |
---|
2788 | \end{cfa} |
---|
2789 | \end{enumerate} |
---|
2790 | |
---|
2791 | \begin{comment} |
---|
2792 | #include <fstream> |
---|
2793 | #include <string.h> // strcpy |
---|
2794 | |
---|
2795 | int main( void ) { |
---|
2796 | int x = 1, y = 2, z = 3; |
---|
2797 | sout | x | y | z | endl; |
---|
2798 | [int, [ int, int ] ] t1 = [ 1, [ 2, 3 ] ], t2 = [ 4, [ 5, 6 ] ]; |
---|
2799 | sout | t1 | t2 | endl; // print tuples |
---|
2800 | sout | x * 3 | y + 1 | z << 2 | x == y | (x | y) | (x || y) | (x > z ? 1 : 2) | endl; |
---|
2801 | sout | 1 | 2 | 3 | endl; |
---|
2802 | sout | '1' | '2' | '3' | endl; |
---|
2803 | sout | 1 | "" | 2 | "" | 3 | endl; |
---|
2804 | sout | "x (" | 1 | "x [" | 2 | "x {" | 3 | "x =" | 4 | "x $" | 5 | "x £" | 6 | "x ¥" |
---|
2805 | | 7 | "x ¡" | 8 | "x ¿" | 9 | "x «" | 10 | endl; |
---|
2806 | sout | 1 | ", x" | 2 | ". x" | 3 | "; x" | 4 | "! x" | 5 | "? x" | 6 | "% x" |
---|
2807 | | 7 | "¢ x" | 8 | "» x" | 9 | ") x" | 10 | "] x" | 11 | "} x" | endl; |
---|
2808 | sout | "x`" | 1 | "`x'" | 2 | "'x\"" | 3 | "\"x:" | 4 | ":x " | 5 | " x\t" | 6 | "\tx" | endl; |
---|
2809 | sout | "x ( " | 1 | " ) x" | 2 | " , x" | 3 | " :x: " | 4 | endl; |
---|
2810 | |
---|
2811 | sepSet( sout, ", $" ); // set separator from " " to ", $" |
---|
2812 | sout | 1 | 2 | 3 | " \"" | sep | "\"" | endl; |
---|
2813 | sepSet( sout, " " ); // reset separator to " " |
---|
2814 | sout | 1 | 2 | 3 | " \"" | sepGet( sout ) | "\"" | endl; |
---|
2815 | |
---|
2816 | char store[sepSize]; |
---|
2817 | strcpy( store, sepGet( sout ) ); |
---|
2818 | sepSet( sout, "_" ); |
---|
2819 | sout | 1 | 2 | 3 | endl; |
---|
2820 | sepSet( sout, store ); |
---|
2821 | sout | 1 | 2 | 3 | endl; |
---|
2822 | |
---|
2823 | sepSetTuple( sout, " " ); // set tuple separator from ", " to " " |
---|
2824 | sout | t1 | t2 | " \"" | sepTuple | "\"" | endl; |
---|
2825 | sepSetTuple( sout, ", " ); // reset tuple separator to ", " |
---|
2826 | sout | t1 | t2 | " \"" | sepGetTuple( sout ) | "\"" | endl; |
---|
2827 | |
---|
2828 | sout | sepDisable | 1 | 2 | 3 | endl; // globally turn off implicit separator |
---|
2829 | sout | sepEnable | 1 | 2 | 3 | endl; // globally turn on implicit separator |
---|
2830 | |
---|
2831 | sout | 1 | sepOff | 2 | 3 | endl; // locally turn on implicit separator |
---|
2832 | sout | sepDisable | 1 | sepOn | 2 | 3 | endl; // globally turn off implicit separator |
---|
2833 | sout | sepEnable; |
---|
2834 | sout | t1 | sepOff | t2 | endl; // locally turn on/off implicit separator |
---|
2835 | |
---|
2836 | sout | sepOn | 1 | 2 | 3 | sepOn | endl ; // sepOn does nothing at start/end of line |
---|
2837 | sout | sep | 1 | 2 | 3 | sep | endl ; // use sep to print separator at start/end of line |
---|
2838 | } |
---|
2839 | |
---|
2840 | // Local Variables: // |
---|
2841 | // tab-width: 4 // |
---|
2842 | // fill-column: 100 // |
---|
2843 | // End: // |
---|
2844 | \end{comment} |
---|
2845 | %$ |
---|
2846 | |
---|
2847 | |
---|
2848 | \section{Types} |
---|
2849 | |
---|
2850 | \subsection{Type Definitions} |
---|
2851 | |
---|
2852 | \CFA allows users to define new types using the keyword type. |
---|
2853 | |
---|
2854 | \begin{cfa} |
---|
2855 | // SensorValue is a distinct type and represented as an int |
---|
2856 | type SensorValue = int; |
---|
2857 | \end{cfa} |
---|
2858 | |
---|
2859 | 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. |
---|
2860 | This means that users can define distinct function overloads for the new type (see Overloading for more information). |
---|
2861 | For example: |
---|
2862 | |
---|
2863 | \begin{cfa} |
---|
2864 | type SensorValue = int; |
---|
2865 | void printValue(int v) {...} |
---|
2866 | void printValue(SensorValue v) {...} |
---|
2867 | void process(int v) {...} |
---|
2868 | |
---|
2869 | SensorValue s = ...; |
---|
2870 | |
---|
2871 | printValue(s); // calls version with SensorValue argument |
---|
2872 | |
---|
2873 | printValue((int) s); // calls version with int argument |
---|
2874 | |
---|
2875 | process(s); // implicit conversion to int |
---|
2876 | \end{cfa} |
---|
2877 | |
---|
2878 | If SensorValue was defined with a typedef, then these two print functions would not have unique signatures. |
---|
2879 | This can be very useful to create a distinct type that has the same representation as another type. |
---|
2880 | |
---|
2881 | The compiler will assume it can safely convert from the old type to the new type, implicitly. |
---|
2882 | Users may override this and define a function that must be called to convert from one type to another. |
---|
2883 | |
---|
2884 | \begin{cfa} |
---|
2885 | type SensorValue = int; |
---|
2886 | // ()? is the overloaded conversion operator identifier |
---|
2887 | // This function converts an int to a SensorValue |
---|
2888 | SensorValue ()?(int val) { |
---|
2889 | ... |
---|
2890 | } |
---|
2891 | void process(int v) {...} |
---|
2892 | |
---|
2893 | SensorValue s = ...; |
---|
2894 | process(s); // implicit call to conversion operator |
---|
2895 | \end{cfa} |
---|
2896 | |
---|
2897 | In many cases, it is not desired for the compiler to do this implicit conversion. |
---|
2898 | To avoid that, the user can use the explicit modifier on the conversion operator. |
---|
2899 | Any places where the conversion is needed but not explicit (with a cast), will result in a compile-time error. |
---|
2900 | |
---|
2901 | \begin{cfa} |
---|
2902 | type SensorValue = int; |
---|
2903 | |
---|
2904 | // conversion from int to SensorValue; must be explicit |
---|
2905 | explicit SensorValue ()?(int val) { |
---|
2906 | ... |
---|
2907 | } |
---|
2908 | |
---|
2909 | void process(int v) {...} |
---|
2910 | |
---|
2911 | SensorValue s = ...; |
---|
2912 | process(s); // implicit cast to int: compile-time error |
---|
2913 | process((int) s); // explicit cast to int: calls conversion func |
---|
2914 | \end{cfa} |
---|
2915 | |
---|
2916 | The conversion may not require any code, but still need to be explicit; in that case, the syntax can be simplified to: |
---|
2917 | \begin{cfa} |
---|
2918 | type SensorValue = int; |
---|
2919 | explicit SensorValue ()?(int); |
---|
2920 | void process(int v) {...} |
---|
2921 | |
---|
2922 | SensorValue s = ...; |
---|
2923 | process(s); // compile-time error |
---|
2924 | process((int) s); // type is converted, no function is called |
---|
2925 | \end{cfa} |
---|
2926 | |
---|
2927 | |
---|
2928 | \subsection{Structures} |
---|
2929 | |
---|
2930 | Structures in \CFA are basically the same as structures in C. |
---|
2931 | A structure is defined with the same syntax as in C. |
---|
2932 | When referring to a structure in \CFA, users may omit the struct keyword. |
---|
2933 | \begin{cfa} |
---|
2934 | struct Point { |
---|
2935 | double x; |
---|
2936 | double y; |
---|
2937 | }; |
---|
2938 | |
---|
2939 | Point p = {0.0, 0.0}; |
---|
2940 | \end{cfa} |
---|
2941 | |
---|
2942 | \CFA does not support inheritance among types, but instead uses composition to enable reuse of structure fields. |
---|
2943 | Composition is achieved by embedding one type into another. |
---|
2944 | 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. |
---|
2945 | Embedding types is achieved using anonymous members. |
---|
2946 | For example, using Point from above: |
---|
2947 | \begin{cfa} |
---|
2948 | void foo(Point p); |
---|
2949 | |
---|
2950 | struct ColoredPoint { |
---|
2951 | Point; // anonymous member (no identifier) |
---|
2952 | int Color; |
---|
2953 | }; |
---|
2954 | ... |
---|
2955 | ColoredPoint cp = ...; |
---|
2956 | cp.x = 10.3; // x from Point is accessed directly |
---|
2957 | cp.color = 0x33aaff; // color is accessed normally |
---|
2958 | foo(cp); // cp can be used directly as a Point |
---|
2959 | \end{cfa} |
---|
2960 | |
---|
2961 | |
---|
2962 | \section{Constructors and Destructors} |
---|
2963 | |
---|
2964 | \CFA supports C initialization of structures, but it also adds constructors for more advanced initialization. |
---|
2965 | Additionally, \CFA adds destructors that are called when a variable is deallocated (variable goes out of scope or object is deleted). |
---|
2966 | These functions take a reference to the structure as a parameter (see References for more information). |
---|
2967 | |
---|
2968 | \begin{figure} |
---|
2969 | \begin{cfa} |
---|
2970 | struct Widget { |
---|
2971 | int id; |
---|
2972 | float size; |
---|
2973 | Parts *optionalParts; |
---|
2974 | }; |
---|
2975 | |
---|
2976 | // ?{} is the constructor operator identifier |
---|
2977 | // The first argument is a reference to the type to initialize |
---|
2978 | // Subsequent arguments can be specified for initialization |
---|
2979 | |
---|
2980 | void ?{}(Widget &w) { // default constructor |
---|
2981 | w.id = -1; |
---|
2982 | w.size = 0.0; |
---|
2983 | w.optionalParts = 0; |
---|
2984 | } |
---|
2985 | |
---|
2986 | // constructor with values (does not need to include all fields) |
---|
2987 | void ?{}(Widget &w, int id, float size) { |
---|
2988 | w.id = id; |
---|
2989 | w.size = size; |
---|
2990 | w.optionalParts = 0; |
---|
2991 | } |
---|
2992 | |
---|
2993 | // ^? is the destructor operator identifier |
---|
2994 | void ^?(Widget &w) { // destructor |
---|
2995 | w.id = 0; |
---|
2996 | w.size = 0.0; |
---|
2997 | if (w.optionalParts != 0) { |
---|
2998 | // This is the only pointer to optionalParts, free it |
---|
2999 | free(w.optionalParts); |
---|
3000 | w.optionalParts = 0; |
---|
3001 | } |
---|
3002 | } |
---|
3003 | |
---|
3004 | Widget baz; // reserve space only |
---|
3005 | Widget foo{}; // calls default constructor |
---|
3006 | Widget bar{23, 2.45}; // calls constructor with values |
---|
3007 | baz{24, 0.91}; // calls constructor with values |
---|
3008 | ?{}(baz, 24, 0.91}; // explicit call to constructor |
---|
3009 | ^bar; // explicit call to destructor |
---|
3010 | ^?(bar); // explicit call to destructor |
---|
3011 | \end{cfa} |
---|
3012 | \caption{Constructors and Destructors} |
---|
3013 | \end{figure} |
---|
3014 | |
---|
3015 | |
---|
3016 | \section{Overloading} |
---|
3017 | |
---|
3018 | Overloading refers to the capability of a programmer to define and use multiple objects in a program with the same name. |
---|
3019 | In \CFA, a declaration may overload declarations from outer scopes with the same name, instead of hiding them as is the case in C. |
---|
3020 | This may cause identical C and \CFA programs to behave differently. |
---|
3021 | The compiler selects the appropriate object (overload resolution) based on context information at the place where it is used. |
---|
3022 | Overloading allows programmers to give functions with different signatures but similar semantics the same name, simplifying the interface to users. |
---|
3023 | 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. |
---|
3024 | \CFA allows overloading of functions, operators, variables, and even the constants 0 and 1. |
---|
3025 | |
---|
3026 | The compiler follows some overload resolution rules to determine the best interpretation of all of these overloads. |
---|
3027 | The best valid interpretations are the valid interpretations that use the fewest unsafe conversions. |
---|
3028 | Of these, the best are those where the functions and objects involved are the least polymorphic. |
---|
3029 | Of these, the best have the lowest total conversion cost, including all implicit conversions in the argument expressions. |
---|
3030 | Of these, the best have the highest total conversion cost for the implicit conversions (if any) applied to the argument expressions. |
---|
3031 | If there is no single best valid interpretation, or if the best valid interpretation is ambiguous, then the resulting interpretation is ambiguous. |
---|
3032 | For details about type inference and overload resolution, please see the \CFA Language Specification. |
---|
3033 | \begin{cfa} |
---|
3034 | int foo(int a, int b) { |
---|
3035 | float sum = 0.0; |
---|
3036 | float special = 1.0; |
---|
3037 | { |
---|
3038 | int sum = 0; |
---|
3039 | // both the float and int versions of sum are available |
---|
3040 | float special = 4.0; |
---|
3041 | // this inner special hides the outer version |
---|
3042 | ... |
---|
3043 | } |
---|
3044 | ... |
---|
3045 | } |
---|
3046 | \end{cfa} |
---|
3047 | |
---|
3048 | |
---|
3049 | \subsection{Overloaded Constant} |
---|
3050 | |
---|
3051 | The constants 0 and 1 have special meaning. |
---|
3052 | In \CFA, as in C, all scalar types can be incremented and |
---|
3053 | decremented, which is defined in terms of adding or subtracting 1. |
---|
3054 | The operations ©&&©, ©||©, and ©!© can be applied to any scalar arguments and are defined in terms of comparison against 0 (ex. ©(a && b)© becomes ©(a != 0 && b != 0)©). |
---|
3055 | |
---|
3056 | In C, the integer constants 0 and 1 suffice because the integer promotion rules can convert them to any arithmetic type, and the rules for pointer expressions treat constant expressions evaluating to 0 as a special case. |
---|
3057 | However, user-defined arithmetic types often need the equivalent of a 1 or 0 for their functions or operators, polymorphic functions often need 0 and 1 constants of a type matching their polymorphic parameters, and user-defined pointer-like types may need a null value. |
---|
3058 | Defining special constants for a user-defined type is more efficient than defining a conversion to the type from ©_Bool©. |
---|
3059 | |
---|
3060 | Why just 0 and 1? Why not other integers? No other integers have special status in C. |
---|
3061 | A facility that let programmers declare specific constants..const Rational 12., for instance. would not be much of an improvement. |
---|
3062 | Some facility for defining the creation of values of programmer-defined types from arbitrary integer tokens would be needed. |
---|
3063 | The complexity of such a feature does not seem worth the gain. |
---|
3064 | |
---|
3065 | For example, to define the constants for a complex type, the programmer would define the following: |
---|
3066 | |
---|
3067 | \begin{cfa} |
---|
3068 | struct Complex { |
---|
3069 | double real; |
---|
3070 | double imaginary; |
---|
3071 | } |
---|
3072 | |
---|
3073 | const Complex 0 = {0, 0}; |
---|
3074 | const Complex 1 = {1, 0}; |
---|
3075 | ... |
---|
3076 | |
---|
3077 | Complex a = 0; |
---|
3078 | ... |
---|
3079 | |
---|
3080 | a++; |
---|
3081 | ... |
---|
3082 | if (a) { // same as if (a == 0) |
---|
3083 | ... |
---|
3084 | } |
---|
3085 | \end{cfa} |
---|
3086 | |
---|
3087 | |
---|
3088 | \subsection{Variable Overloading} |
---|
3089 | |
---|
3090 | The overload rules of \CFA allow a programmer to define multiple variables with the same name, but different types. |
---|
3091 | 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. |
---|
3092 | For example, a developer may want to do the following: |
---|
3093 | \begin{cfa} |
---|
3094 | int pi = 3; |
---|
3095 | float pi = 3.14; |
---|
3096 | char pi = .p.; |
---|
3097 | \end{cfa} |
---|
3098 | |
---|
3099 | |
---|
3100 | \subsection{Function Overloading} |
---|
3101 | |
---|
3102 | 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). |
---|
3103 | |
---|
3104 | The examples below give some basic intuition about how the resolution works. |
---|
3105 | \begin{cfa} |
---|
3106 | // Choose the one with less conversions |
---|
3107 | int doSomething(int value) {...} // option 1 |
---|
3108 | int doSomething(short value) {...} // option 2 |
---|
3109 | |
---|
3110 | int a, b = 4; |
---|
3111 | short c = 2; |
---|
3112 | |
---|
3113 | a = doSomething(b); // chooses option 1 |
---|
3114 | a = doSomething(c); // chooses option 2 |
---|
3115 | |
---|
3116 | // Choose the specialized version over the generic |
---|
3117 | |
---|
3118 | generic(type T) |
---|
3119 | T bar(T rhs, T lhs) {...} // option 3 |
---|
3120 | float bar(float rhs, float lhs){...} // option 4 |
---|
3121 | float a, b, c; |
---|
3122 | double d, e, f; |
---|
3123 | c = bar(a, b); // chooses option 4 |
---|
3124 | |
---|
3125 | // specialization is preferred over unsafe conversions |
---|
3126 | |
---|
3127 | f = bar(d, e); // chooses option 5 |
---|
3128 | \end{cfa} |
---|
3129 | |
---|
3130 | |
---|
3131 | \subsection{Operator Overloading} |
---|
3132 | |
---|
3133 | \CFA also allows operators to be overloaded, to simplify the use of user-defined types. |
---|
3134 | 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. |
---|
3135 | \CFA uses the following special identifiers to name overloaded operators: |
---|
3136 | |
---|
3137 | \begin{table}[hbt] |
---|
3138 | \hfil |
---|
3139 | \begin{tabular}[t]{ll} |
---|
3140 | %identifier & operation \\ \hline |
---|
3141 | ©?[?]© & subscripting \impl{?[?]}\\ |
---|
3142 | ©?()© & function call \impl{?()}\\ |
---|
3143 | ©?++© & postfix increment \impl{?++}\\ |
---|
3144 | ©?--© & postfix decrement \impl{?--}\\ |
---|
3145 | ©++?© & prefix increment \impl{++?}\\ |
---|
3146 | ©--?© & prefix decrement \impl{--?}\\ |
---|
3147 | ©*?© & dereference \impl{*?}\\ |
---|
3148 | ©+?© & unary plus \impl{+?}\\ |
---|
3149 | ©-?© & arithmetic negation \impl{-?}\\ |
---|
3150 | ©~?© & bitwise negation \impl{~?}\\ |
---|
3151 | ©!?© & logical complement \impl{"!?}\\ |
---|
3152 | ©?*?© & multiplication \impl{?*?}\\ |
---|
3153 | ©?/?© & division \impl{?/?}\\ |
---|
3154 | \end{tabular}\hfil |
---|
3155 | \begin{tabular}[t]{ll} |
---|
3156 | %identifier & operation \\ \hline |
---|
3157 | ©?%?© & remainder \impl{?%?}\\ |
---|
3158 | ©?+?© & addition \impl{?+?}\\ |
---|
3159 | ©?-?© & subtraction \impl{?-?}\\ |
---|
3160 | ©?<<?© & left shift \impl{?<<?}\\ |
---|
3161 | ©?>>?© & right shift \impl{?>>?}\\ |
---|
3162 | ©?<?© & less than \impl{?<?}\\ |
---|
3163 | ©?<=?© & less than or equal \impl{?<=?}\\ |
---|
3164 | ©?>=?© & greater than or equal \impl{?>=?}\\ |
---|
3165 | ©?>?© & greater than \impl{?>?}\\ |
---|
3166 | ©?==?© & equality \impl{?==?}\\ |
---|
3167 | ©?!=?© & inequality \impl{?"!=?}\\ |
---|
3168 | ©?&?© & bitwise AND \impl{?&?}\\ |
---|
3169 | \end{tabular}\hfil |
---|
3170 | \begin{tabular}[t]{ll} |
---|
3171 | %identifier & operation \\ \hline |
---|
3172 | ©?^?© & exclusive OR \impl{?^?}\\ |
---|
3173 | ©?|?© & inclusive OR \impl{?"|?}\\ |
---|
3174 | ©?=?© & simple assignment \impl{?=?}\\ |
---|
3175 | ©?*=?© & multiplication assignment \impl{?*=?}\\ |
---|
3176 | ©?/=?© & division assignment \impl{?/=?}\\ |
---|
3177 | ©?%=?© & remainder assignment \impl{?%=?}\\ |
---|
3178 | ©?+=?© & addition assignment \impl{?+=?}\\ |
---|
3179 | ©?-=?© & subtraction assignment \impl{?-=?}\\ |
---|
3180 | ©?<<=?© & left-shift assignment \impl{?<<=?}\\ |
---|
3181 | ©?>>=?© & right-shift assignment \impl{?>>=?}\\ |
---|
3182 | ©?&=?© & bitwise AND assignment \impl{?&=?}\\ |
---|
3183 | ©?^=?© & exclusive OR assignment \impl{?^=?}\\ |
---|
3184 | ©?|=?© & inclusive OR assignment \impl{?"|=?}\\ |
---|
3185 | \end{tabular} |
---|
3186 | \hfil |
---|
3187 | \caption{Operator Identifiers} |
---|
3188 | \label{opids} |
---|
3189 | \end{table} |
---|
3190 | |
---|
3191 | These identifiers are defined such that the question marks in the name identify the location of the operands. |
---|
3192 | These operands represent the parameters to the functions, and define how the operands are mapped to the function call. |
---|
3193 | For example, ©a + b© becomes ©?+?(a, b)©. |
---|
3194 | |
---|
3195 | In the example below, a new type, myComplex, is defined with an overloaded constructor, + operator, and string operator. |
---|
3196 | These operators are called using the normal C syntax. |
---|
3197 | |
---|
3198 | \begin{cfa} |
---|
3199 | type Complex = struct { // define a Complex type |
---|
3200 | double real; |
---|
3201 | double imag; |
---|
3202 | } |
---|
3203 | |
---|
3204 | // Constructor with default values |
---|
3205 | |
---|
3206 | void ?{}(Complex &c, double real = 0.0, double imag = 0.0) { |
---|
3207 | c.real = real; |
---|
3208 | c.imag = imag; |
---|
3209 | } |
---|
3210 | |
---|
3211 | Complex ?+?(Complex lhs, Complex rhs) { |
---|
3212 | Complex sum; |
---|
3213 | sum.real = lhs.real + rhs.real; |
---|
3214 | sum.imag = lhs.imag + rhs.imag; |
---|
3215 | return sum; |
---|
3216 | } |
---|
3217 | |
---|
3218 | String ()?(const Complex c) { |
---|
3219 | // use the string conversions for the structure members |
---|
3220 | return (String)c.real + . + . + (String)c.imag + .i.; |
---|
3221 | } |
---|
3222 | ... |
---|
3223 | |
---|
3224 | Complex a, b, c = {1.0}; // constructor for c w/ default imag |
---|
3225 | ... |
---|
3226 | c = a + b; |
---|
3227 | print(.sum = . + c); |
---|
3228 | \end{cfa} |
---|
3229 | |
---|
3230 | |
---|
3231 | \section{Auto Type-Inferencing} |
---|
3232 | |
---|
3233 | Auto type-inferencing occurs in a declaration where a variable's type is inferred from its initialization expression type. |
---|
3234 | \begin{quote2} |
---|
3235 | \begin{tabular}{@{}l@{\hspace{3em}}ll@{}} |
---|
3236 | \multicolumn{1}{c@{\hspace{3em}}}{\textbf{\CC}} & \multicolumn{1}{c}{\textbf{\Indexc{gcc}}} \\ |
---|
3237 | \begin{cfa} |
---|
3238 | |
---|
3239 | auto j = 3.0 * 4; |
---|
3240 | int i; |
---|
3241 | auto k = i; |
---|
3242 | \end{cfa} |
---|
3243 | & |
---|
3244 | \begin{cfa} |
---|
3245 | #define expr 3.0 * i |
---|
3246 | typeof(expr) j = expr; |
---|
3247 | int i; |
---|
3248 | typeof(i) k = i; |
---|
3249 | \end{cfa} |
---|
3250 | & |
---|
3251 | \begin{cfa} |
---|
3252 | |
---|
3253 | // use type of initialization expression |
---|
3254 | |
---|
3255 | // use type of primary variable |
---|
3256 | \end{cfa} |
---|
3257 | \end{tabular} |
---|
3258 | \end{quote2} |
---|
3259 | The two important capabilities are: |
---|
3260 | \begin{itemize} |
---|
3261 | \item |
---|
3262 | preventing having to determine or write out long generic types, |
---|
3263 | \item |
---|
3264 | ensure secondary variables, related to a primary variable, always have the same type. |
---|
3265 | \end{itemize} |
---|
3266 | |
---|
3267 | In \CFA, ©typedef© provides a mechanism to alias long type names with short ones, both globally and locally, but not eliminate the use of the short name. |
---|
3268 | \Indexc{gcc} provides ©typeof© to declare a secondary variable from a primary variable. |
---|
3269 | \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. |
---|
3270 | Only for overloaded routines \emph{with the same return type} is variable type-inferencing possible. |
---|
3271 | Finally, ©auto© presents the programming problem of tracking down a type when the type is actually needed. |
---|
3272 | For example, given |
---|
3273 | \begin{cfa} |
---|
3274 | auto j = ®...® |
---|
3275 | \end{cfa} |
---|
3276 | and the need to write a routine to compute using ©j© |
---|
3277 | \begin{cfa} |
---|
3278 | void rtn( ®...® parm ); |
---|
3279 | rtn( j ); |
---|
3280 | \end{cfa} |
---|
3281 | A programmer must work backwards to determine the type of ©j©'s initialization expression, reconstructing the possibly long generic type-name. |
---|
3282 | In this situation, having the type name or a short alias is very useful. |
---|
3283 | |
---|
3284 | There is also the conundrum in type inferencing of when to \emph{\Index{brand}} a type. |
---|
3285 | That is, when is the type of the variable more important than the type of its initialization expression. |
---|
3286 | For example, if a change is made in an initialization expression, it can cause hundreds or thousands of cascading type changes and/or errors. |
---|
3287 | At some point, a programmer wants the type of the variable to remain constant and the expression to be in error when it changes. |
---|
3288 | |
---|
3289 | Given ©typedef© and ©typeof© in \CFA, and the strong need to use the type of left-hand side in inferencing, auto type-inferencing is not supported at this time. |
---|
3290 | Should a significant need arise, this feature can be revisited. |
---|
3291 | |
---|
3292 | |
---|
3293 | \begin{comment} |
---|
3294 | \section{Generics} |
---|
3295 | |
---|
3296 | \CFA supports parametric polymorphism to allow users to define generic functions and types. |
---|
3297 | Generics allow programmers to use type variables in place of concrete types so that the code can be reused with multiple types. |
---|
3298 | The type parameters can be restricted to satisfy a set of constraints. |
---|
3299 | This enables \CFA to build fully compiled generic functions and types, unlike other languages like \Index*[C++]{\CC{}} where templates are expanded or must be explicitly instantiated. |
---|
3300 | |
---|
3301 | |
---|
3302 | \subsection{Generic Functions} |
---|
3303 | |
---|
3304 | Generic functions in \CFA are similar to template functions in \Index*[C++]{\CC{}}, and will sometimes be expanded into specialized versions, just like in \CC. |
---|
3305 | 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. |
---|
3306 | This means that compiled libraries can contain generic functions that can be used by programs linked with them (statically or dynamically). |
---|
3307 | Another advantage over \CC templates is unlike templates, generic functions are statically checked, even without being instantiated. |
---|
3308 | |
---|
3309 | A simple example of using Do.s parametric polymorphism to create a generic swap function would look like this: |
---|
3310 | |
---|
3311 | \begin{cfa} |
---|
3312 | generic(type T) |
---|
3313 | void swap(T &a, T &b) { |
---|
3314 | T tmp = a; |
---|
3315 | a = b; |
---|
3316 | b = a; |
---|
3317 | } |
---|
3318 | |
---|
3319 | int a, b; |
---|
3320 | swap(a, b); |
---|
3321 | |
---|
3322 | Point p1, p2; |
---|
3323 | swap(p1, p2); |
---|
3324 | \end{cfa} |
---|
3325 | |
---|
3326 | Here, instead of specifying types for the parameters a and b, the function has a generic type parameter, type T. |
---|
3327 | 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. |
---|
3328 | |
---|
3329 | |
---|
3330 | \subsection{Bounded Quantification} |
---|
3331 | |
---|
3332 | Some generic functions only work (or make sense) for any type that satisfies a given property. |
---|
3333 | For example, here is a function to pick the minimum of two values of some type. |
---|
3334 | \begin{cfa} |
---|
3335 | generic (type T | bool ?<?(T, T) ) |
---|
3336 | |
---|
3337 | T min( T a, T b ) { |
---|
3338 | return a < b ? a : b; |
---|
3339 | } |
---|
3340 | \end{cfa} |
---|
3341 | |
---|
3342 | 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. |
---|
3343 | The ordering function used here is the less than operator, <. |
---|
3344 | The syntax used to reference the operator is discussed in further detail in Operator Overloading. |
---|
3345 | In \CFA, this assertion on the type of a generic is written as the bound, (type T | bool ?<?(T, T)). |
---|
3346 | 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. |
---|
3347 | |
---|
3348 | Bounds can also involve multiple types, and multiple requirements, as shown below: |
---|
3349 | \begin{cfa} |
---|
3350 | generic (type T, type U | { T foo(T, U); U bar(U); }) |
---|
3351 | |
---|
3352 | T baz(T t, U u) { |
---|
3353 | return foo(t, bar(u)); |
---|
3354 | } |
---|
3355 | \end{cfa} |
---|
3356 | |
---|
3357 | |
---|
3358 | \subsection{Interfaces} |
---|
3359 | |
---|
3360 | Type bounds as shown above are not very informative, merely requiring that a function exists with the right name and type. |
---|
3361 | Suppose you try to call a polymorphic function and \CFA gives you an error that int combine(int, int) is not defined. |
---|
3362 | 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. |
---|
3363 | The function signature doesn't say. |
---|
3364 | |
---|
3365 | Interfaces gather together a set of function signatures under a common name, which solves two problems. |
---|
3366 | First, an interface name can be used in type bounds instead of function signatures. |
---|
3367 | This avoids repetition when a bound is used in many functions. |
---|
3368 | Second, interfaces explicitly document the existence of a commonly used set of functionality, making programs easier to understand. |
---|
3369 | \begin{cfa} |
---|
3370 | generic (type T) |
---|
3371 | interface Orderable { |
---|
3372 | bool ?<?(T, T); |
---|
3373 | }; |
---|
3374 | |
---|
3375 | generic (type T | Orderable(T)) |
---|
3376 | T min( T a, T b ) { |
---|
3377 | return a < b ? a : b; |
---|
3378 | } |
---|
3379 | \end{cfa} |
---|
3380 | |
---|
3381 | This definition of the interface Orderable makes the generic function min easier to read and understand. |
---|
3382 | Orderable can also be reused for other generic functions, max for example. |
---|
3383 | Interfaces can also build on top of other interfaces. |
---|
3384 | For example: |
---|
3385 | \begin{cfa} |
---|
3386 | generic (type T | Orderable(T) |
---|
3387 | interface FooBarable { |
---|
3388 | int foo(T, T); |
---|
3389 | int Bar(T, T); |
---|
3390 | }; |
---|
3391 | \end{cfa} |
---|
3392 | |
---|
3393 | The FooBarable interface specifies all of the bounds of the Orderable interface, plus the additional bounds specified in its definition. |
---|
3394 | A type does not need to specify that it satisfies any interface, the compiler can figure this out at compile time. |
---|
3395 | 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. |
---|
3396 | |
---|
3397 | |
---|
3398 | \subsection{Generic Typedefs} |
---|
3399 | |
---|
3400 | Type synonyms can be defined generically using the typedef keyword together with a generic type annotation. |
---|
3401 | These can be used to abbreviate complicated type expressions, especially in generic code. |
---|
3402 | \begin{cfa} |
---|
3403 | // typedef the generic function pointers for later use |
---|
3404 | |
---|
3405 | generic(type T) |
---|
3406 | typedef int (*predicate)(T); |
---|
3407 | generic(type Captured, type T) |
---|
3408 | typedef void (*callback)(Captured, T); |
---|
3409 | |
---|
3410 | generic(type T) |
---|
3411 | void find(int length, T *array, |
---|
3412 | predicate(T) p, callback(void *, T)f) { |
---|
3413 | int i; |
---|
3414 | for (i = 0; i < length; i++) |
---|
3415 | if (p(array[i])) f(NULL, array[i]); |
---|
3416 | } |
---|
3417 | \end{cfa} |
---|
3418 | |
---|
3419 | |
---|
3420 | \subsection{Generic Types} |
---|
3421 | |
---|
3422 | Generic types are defined using the same mechanisms as those described above for generic functions. |
---|
3423 | This feature allows users to create types that have one or more fields that use generic parameters as types, similar to a template classes in \Index*[C++]{\CC{}}. |
---|
3424 | 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. |
---|
3425 | In C, something like this would have to be done using void pointers and unsafe casting. |
---|
3426 | 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. |
---|
3427 | This means that a \CFA generic type from a compiled library can be used with any type that satisfies the bounds. |
---|
3428 | |
---|
3429 | The syntax for defining a generic type looks very similar to that of a generic function. |
---|
3430 | Generic types support bounds and interfaces, using the same syntax as generic functions. |
---|
3431 | \begin{cfa} |
---|
3432 | generic (type T) |
---|
3433 | struct LinkedListElem { |
---|
3434 | T elem; |
---|
3435 | LinkedListElem(T) *next; |
---|
3436 | }; |
---|
3437 | |
---|
3438 | LinkedListElem *++?(LinkedListElem **elem) { |
---|
3439 | return *elem = elem->next; |
---|
3440 | } |
---|
3441 | |
---|
3442 | generic (type T) |
---|
3443 | struct LinkedList { |
---|
3444 | LinkedListElem(T) *head; |
---|
3445 | unsigned int size; |
---|
3446 | } |
---|
3447 | |
---|
3448 | generic (type T | bool ?==?(T, T)) |
---|
3449 | bool contains(LinkedList(T) *list, T elem) { |
---|
3450 | for(LinkedListElem *iter = list->head; iter != 0; ++iter) { |
---|
3451 | if (iter->elem == elem) return true; |
---|
3452 | } |
---|
3453 | return false; |
---|
3454 | } |
---|
3455 | \end{cfa} |
---|
3456 | |
---|
3457 | |
---|
3458 | \section{Safety} |
---|
3459 | |
---|
3460 | Safety, along with productivity, is a key goal of Do. |
---|
3461 | This section discusses the safety features that have been included in \CFA to help programmers create more stable, reliable, and secure code. |
---|
3462 | |
---|
3463 | |
---|
3464 | \subsection{Exceptions} |
---|
3465 | |
---|
3466 | \CFA introduces support for exceptions as an easier way to recover from exceptional conditions that may be detected within a block of code. |
---|
3467 | In C, developers can use error codes and special return values to report to a caller that an error occurred in a function. |
---|
3468 | The major problem with error codes is that they can be easily ignored by the caller. |
---|
3469 | 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. |
---|
3470 | An unhandled exception on the other hand will cause a crash, revealing the original source of the erroneous state. |
---|
3471 | |
---|
3472 | Exceptions in \CFA allow a different type of control flow. |
---|
3473 | 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. |
---|
3474 | The exception is immediately re-thrown from the parent block unless it is caught as described below. |
---|
3475 | \CFA uses keywords similar to \Index*[C++]{\CC{}} for exception handling. |
---|
3476 | An exception is thrown using a throw statement, which accepts one argument. |
---|
3477 | |
---|
3478 | \begin{cfa} |
---|
3479 | ... |
---|
3480 | |
---|
3481 | throw 13; |
---|
3482 | |
---|
3483 | ... |
---|
3484 | \end{cfa} |
---|
3485 | |
---|
3486 | An exception can be caught using a catch statement, which specifies the type of the exception it can catch. |
---|
3487 | A catch is specified immediately after a guarded block to signify that it can catch an exception from that block. |
---|
3488 | A guarded block is specified using the try keyword, followed by a block of code inside of curly braces. |
---|
3489 | |
---|
3490 | \begin{cfa} |
---|
3491 | ... |
---|
3492 | |
---|
3493 | try { |
---|
3494 | throw 13; |
---|
3495 | } |
---|
3496 | catch(int e) { |
---|
3497 | printf(.caught an exception: %d\n., e); |
---|
3498 | } |
---|
3499 | \end{cfa} |
---|
3500 | \end{comment} |
---|
3501 | |
---|
3502 | |
---|
3503 | \subsection{Memory Management} |
---|
3504 | |
---|
3505 | |
---|
3506 | \subsubsection{Manual Memory Management} |
---|
3507 | |
---|
3508 | Using malloc and free to dynamically allocate memory exposes several potential, and common, errors. |
---|
3509 | First, malloc breaks type safety because it returns a pointer to void. |
---|
3510 | There is no relationship between the type that the returned pointer is cast to, and the amount of memory allocated. |
---|
3511 | This problem is solved with a type-safe malloc. |
---|
3512 | Do.s type-safe malloc does not take any arguments for size. |
---|
3513 | Instead, it infers the type based on the return value, and then allocates space for the inferred type. |
---|
3514 | |
---|
3515 | \begin{cfa} |
---|
3516 | float *f = malloc(); // allocates the size of a float |
---|
3517 | |
---|
3518 | struct S { |
---|
3519 | int i, j, k; |
---|
3520 | }; |
---|
3521 | |
---|
3522 | struct S *s = malloc(); // allocates the size of a struct S |
---|
3523 | \end{cfa} |
---|
3524 | |
---|
3525 | In addition to the improved malloc, \CFA also provides a technique for combining allocation and initialization into one step, using the new function. |
---|
3526 | 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. |
---|
3527 | |
---|
3528 | \begin{cfa} |
---|
3529 | type Complex = struct { |
---|
3530 | float real; |
---|
3531 | float imag; |
---|
3532 | }; |
---|
3533 | |
---|
3534 | // default constructor |
---|
3535 | |
---|
3536 | void ?{}(Complex &c) { |
---|
3537 | c.real = 0.0; |
---|
3538 | c.imag = 0.0; |
---|
3539 | } |
---|
3540 | |
---|
3541 | |
---|
3542 | |
---|
3543 | // 2 parameter constructor |
---|
3544 | |
---|
3545 | void ?{}(Complex &c, float real, float imag) { |
---|
3546 | c.real = real; |
---|
3547 | c.imag = imag; |
---|
3548 | } |
---|
3549 | |
---|
3550 | |
---|
3551 | int main() { |
---|
3552 | Complex c1; // No constructor is called |
---|
3553 | Complex c2{}; // Default constructor called |
---|
3554 | Complex c3{1.0, -1.0}; // 2 parameter constructor is called |
---|
3555 | |
---|
3556 | Complex *p1 = malloc(); // allocate |
---|
3557 | Complex *p2 = new(); // allocate + default constructor |
---|
3558 | Complex *p3 = new(0.5, 1.0); // allocate + 2 param constructor |
---|
3559 | } |
---|
3560 | \end{cfa} |
---|
3561 | |
---|
3562 | |
---|
3563 | \subsubsection{Automatic Memory Management} |
---|
3564 | |
---|
3565 | \CFA may also support automatic memory management to further improve safety. |
---|
3566 | 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. |
---|
3567 | This feature requires further investigation. |
---|
3568 | \CFA will not have a garbage collector, but might use some kind of region-based memory management. |
---|
3569 | |
---|
3570 | |
---|
3571 | \begin{comment} |
---|
3572 | \subsection{Unsafe C Constructs} |
---|
3573 | |
---|
3574 | C programmers are able to access all of the low-level tricks that are sometimes needed for close-to-the-hardware programming. |
---|
3575 | Some of these practices however are often error-prone and difficult to read and maintain. |
---|
3576 | Since \CFA is designed to be safer than C, such constructs are disallowed in \CFA code. |
---|
3577 | 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. |
---|
3578 | This block means that the user is telling the tools, .I know this is unsafe, but I.m going to do it anyway.. |
---|
3579 | |
---|
3580 | 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. |
---|
3581 | Once the full set is decided, the rules will be listed here. |
---|
3582 | \end{comment} |
---|
3583 | |
---|
3584 | |
---|
3585 | \section{Concurrency} |
---|
3586 | |
---|
3587 | Concurrency support in \CFA is implemented on top of a highly efficient runtime system of light-weight, M:N, user level threads. |
---|
3588 | The model integrates concurrency features into the language by making the structure type the core unit of concurrency. |
---|
3589 | All communication occurs through method calls, where data is sent via method arguments, and received via the return value. |
---|
3590 | This enables a very familiar interface to all programmers, even those with no parallel programming experience. |
---|
3591 | It also allows the compiler to do static type checking of all communication, a very important safety feature. |
---|
3592 | This controlled communication with type safety has some similarities with channels in \Index*{Go}, and can actually implement channels exactly, as well as create additional communication patterns that channels cannot. |
---|
3593 | Mutex objects, monitors, are used to contain mutual exclusion within an object and synchronization across concurrent threads. |
---|
3594 | |
---|
3595 | \begin{figure} |
---|
3596 | \begin{cfa} |
---|
3597 | #include <fstream> |
---|
3598 | #include <coroutine> |
---|
3599 | |
---|
3600 | coroutine Fibonacci { |
---|
3601 | int fn; §\C{// used for communication}§ |
---|
3602 | }; |
---|
3603 | void ?{}( Fibonacci * this ) { |
---|
3604 | this->fn = 0; |
---|
3605 | } |
---|
3606 | void main( Fibonacci * this ) { |
---|
3607 | int fn1, fn2; §\C{// retained between resumes}§ |
---|
3608 | this->fn = 0; §\C{// case 0}§ |
---|
3609 | fn1 = this->fn; |
---|
3610 | suspend(); §\C{// return to last resume}§ |
---|
3611 | |
---|
3612 | this->fn = 1; §\C{// case 1}§ |
---|
3613 | fn2 = fn1; |
---|
3614 | fn1 = this->fn; |
---|
3615 | suspend(); §\C{// return to last resume}§ |
---|
3616 | |
---|
3617 | for ( ;; ) { §\C{// general case}§ |
---|
3618 | this->fn = fn1 + fn2; |
---|
3619 | fn2 = fn1; |
---|
3620 | fn1 = this->fn; |
---|
3621 | suspend(); §\C{// return to last resume}§ |
---|
3622 | } // for |
---|
3623 | } |
---|
3624 | int next( Fibonacci * this ) { |
---|
3625 | resume( this ); §\C{// transfer to last suspend}§ |
---|
3626 | return this->fn; |
---|
3627 | } |
---|
3628 | int main() { |
---|
3629 | Fibonacci f1, f2; |
---|
3630 | for ( int i = 1; i <= 10; i += 1 ) { |
---|
3631 | sout | next( &f1 ) | ' ' | next( &f2 ) | endl; |
---|
3632 | } // for |
---|
3633 | } |
---|
3634 | \end{cfa} |
---|
3635 | \caption{Fibonacci Coroutine} |
---|
3636 | \label{f:FibonacciCoroutine} |
---|
3637 | \end{figure} |
---|
3638 | |
---|
3639 | |
---|
3640 | \subsection{Coroutine} |
---|
3641 | |
---|
3642 | \Index{Coroutines} are the precursor to tasks. |
---|
3643 | \VRef[Figure]{f:FibonacciCoroutine} shows a coroutine that computes the \Index*{Fibonacci} numbers. |
---|
3644 | |
---|
3645 | |
---|
3646 | \subsection{Monitors} |
---|
3647 | |
---|
3648 | A monitor is a structure in \CFA which includes implicit locking of its fields. |
---|
3649 | Users of a monitor interact with it just like any structure, but the compiler handles code as needed to ensure mutual exclusion. |
---|
3650 | An example of the definition of a monitor is shown here: |
---|
3651 | \begin{cfa} |
---|
3652 | type Account = monitor { |
---|
3653 | const unsigned long number; // account number |
---|
3654 | float balance; // account balance |
---|
3655 | }; |
---|
3656 | \end{cfa} |
---|
3657 | |
---|
3658 | \begin{figure} |
---|
3659 | \begin{cfa} |
---|
3660 | #include <fstream> |
---|
3661 | #include <kernel> |
---|
3662 | #include <monitor> |
---|
3663 | #include <thread> |
---|
3664 | |
---|
3665 | monitor global_t { |
---|
3666 | int value; |
---|
3667 | }; |
---|
3668 | |
---|
3669 | void ?{}(global_t * this) { |
---|
3670 | this->value = 0; |
---|
3671 | } |
---|
3672 | |
---|
3673 | static global_t global; |
---|
3674 | |
---|
3675 | void increment3( global_t * mutex this ) { |
---|
3676 | this->value += 1; |
---|
3677 | } |
---|
3678 | void increment2( global_t * mutex this ) { |
---|
3679 | increment3( this ); |
---|
3680 | } |
---|
3681 | void increment( global_t * mutex this ) { |
---|
3682 | increment2( this ); |
---|
3683 | } |
---|
3684 | |
---|
3685 | thread MyThread {}; |
---|
3686 | |
---|
3687 | void main( MyThread* this ) { |
---|
3688 | for(int i = 0; i < 1_000_000; i++) { |
---|
3689 | increment( &global ); |
---|
3690 | } |
---|
3691 | } |
---|
3692 | int main(int argc, char* argv[]) { |
---|
3693 | processor p; |
---|
3694 | { |
---|
3695 | MyThread f[4]; |
---|
3696 | } |
---|
3697 | sout | global.value | endl; |
---|
3698 | } |
---|
3699 | \end{cfa} |
---|
3700 | \caption{Atomic-Counter Monitor} |
---|
3701 | \caption{f:AtomicCounterMonitor} |
---|
3702 | \end{figure} |
---|
3703 | |
---|
3704 | \begin{comment} |
---|
3705 | Since a monitor structure includes an implicit locking mechanism, it does not make sense to copy a monitor; |
---|
3706 | it is always passed by reference. |
---|
3707 | 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. |
---|
3708 | When mutex is specified, the compiler inserts locking before executing the body of the function, and unlocking after the body. |
---|
3709 | This means that a function requiring mutual exclusion could block if the lock is already held by another thread. |
---|
3710 | 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. |
---|
3711 | If multiple mutex parameters are specified, they will be locked in parameter order (\ie first parameter is locked first) and unlocked in the |
---|
3712 | reverse order. |
---|
3713 | \begin{cfa} |
---|
3714 | // This function accesses a constant field, it does not require |
---|
3715 | // mutual exclusion |
---|
3716 | |
---|
3717 | export unsigned long getAccountNumber(Account &a) { |
---|
3718 | return a.number; |
---|
3719 | } |
---|
3720 | |
---|
3721 | // This function accesses and modifies a shared field; it |
---|
3722 | // requires mutual exclusion |
---|
3723 | |
---|
3724 | export float withdrawal(mutex Account &a, float amount) { |
---|
3725 | a.balance -= amount; |
---|
3726 | return a.balance; |
---|
3727 | } |
---|
3728 | \end{cfa} |
---|
3729 | |
---|
3730 | Often, one function using a monitor will call another function using that same monitor. |
---|
3731 | If both require mutual exclusion, then the thread would be waiting for itself to release the lock when it calls the inner function. |
---|
3732 | 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. |
---|
3733 | It will still be unlocked the same number of times. |
---|
3734 | An example of this situation is shown below: |
---|
3735 | |
---|
3736 | \begin{cfa} |
---|
3737 | // deleting a job from a worker requires mutual exclusion |
---|
3738 | |
---|
3739 | void deleteJob(mutex Worker &w, Job &j) { |
---|
3740 | ... |
---|
3741 | } |
---|
3742 | |
---|
3743 | // transferring requires mutual exclusion and calls deleteJob |
---|
3744 | |
---|
3745 | void transferJob(mutex Worker &from, Worker &to) { |
---|
3746 | ... |
---|
3747 | deleteJob(j); |
---|
3748 | ... |
---|
3749 | } |
---|
3750 | \end{cfa} |
---|
3751 | \end{comment} |
---|
3752 | |
---|
3753 | |
---|
3754 | \subsection{Tasks} |
---|
3755 | |
---|
3756 | \CFA also provides a simple mechanism for creating and utilizing user level threads. |
---|
3757 | A task provides mutual exclusion like a monitor, and also has its own execution state and a thread of control. |
---|
3758 | Similar to a monitor, a task is defined like a structure: |
---|
3759 | |
---|
3760 | \begin{figure} |
---|
3761 | \begin{cfa} |
---|
3762 | #include <fstream> |
---|
3763 | #include <kernel> |
---|
3764 | #include <stdlib> |
---|
3765 | #include <thread> |
---|
3766 | |
---|
3767 | thread First { signal_once * lock; }; |
---|
3768 | thread Second { signal_once * lock; }; |
---|
3769 | |
---|
3770 | void ?{}( First * this, signal_once* lock ) { this->lock = lock; } |
---|
3771 | void ?{}( Second * this, signal_once* lock ) { this->lock = lock; } |
---|
3772 | |
---|
3773 | void main( First * this ) { |
---|
3774 | for ( int i = 0; i < 10; i += 1 ) { |
---|
3775 | sout | "First : Suspend No." | i + 1 | endl; |
---|
3776 | yield(); |
---|
3777 | } |
---|
3778 | signal( this->lock ); |
---|
3779 | } |
---|
3780 | |
---|
3781 | void main( Second * this ) { |
---|
3782 | wait( this->lock ); |
---|
3783 | for ( int i = 0; i < 10; i += 1 ) { |
---|
3784 | sout | "Second : Suspend No." | i + 1 | endl; |
---|
3785 | yield(); |
---|
3786 | } |
---|
3787 | } |
---|
3788 | |
---|
3789 | int main( void ) { |
---|
3790 | signal_once lock; |
---|
3791 | sout | "User main begin" | endl; |
---|
3792 | { |
---|
3793 | processor p; |
---|
3794 | { |
---|
3795 | First f = { &lock }; |
---|
3796 | Second s = { &lock }; |
---|
3797 | } |
---|
3798 | } |
---|
3799 | sout | "User main end" | endl; |
---|
3800 | } |
---|
3801 | \end{cfa} |
---|
3802 | \caption{Simple Tasks} |
---|
3803 | \label{f:SimpleTasks} |
---|
3804 | \end{figure} |
---|
3805 | |
---|
3806 | |
---|
3807 | \begin{comment} |
---|
3808 | \begin{cfa} |
---|
3809 | type Adder = task { |
---|
3810 | int *row; |
---|
3811 | int size; |
---|
3812 | int &subtotal; |
---|
3813 | } |
---|
3814 | \end{cfa} |
---|
3815 | |
---|
3816 | A task may define a constructor, which will be called upon allocation and run on the caller.s thread. |
---|
3817 | A destructor may also be defined, which is called at deallocation (when a dynamic object is deleted or when a local object goes out of scope). |
---|
3818 | After a task is allocated and initialized, its thread is spawned implicitly and begins executing in its function call method. |
---|
3819 | All tasks must define this function call method, with a void return value and no additional parameters, or the compiler will report an error. |
---|
3820 | Below are example functions for the above Adder task, and its usage to sum up a matrix on multiple threads. |
---|
3821 | (Note that this example is designed to display the syntax and functionality, not the best method to solve this problem) |
---|
3822 | \begin{cfa} |
---|
3823 | void ?{}(Adder &a, int r[], int s, int &st) { // constructor |
---|
3824 | a.row = r; |
---|
3825 | a.size = s; |
---|
3826 | a.subtotal = st; |
---|
3827 | } |
---|
3828 | |
---|
3829 | // implicitly spawn thread and begin execution here |
---|
3830 | |
---|
3831 | void ?()(Adder &a) { |
---|
3832 | int c; |
---|
3833 | subtotal = 0; |
---|
3834 | for (c=0; c<a.size; ++c) { |
---|
3835 | subtotal += row[c]; |
---|
3836 | } |
---|
3837 | } |
---|
3838 | |
---|
3839 | int main() { |
---|
3840 | const int rows = 100, cols = 1000000; |
---|
3841 | int matrix[rows][cols]; |
---|
3842 | int subtotals[rows]; |
---|
3843 | int total = 0; |
---|
3844 | int r; |
---|
3845 | |
---|
3846 | { // create a new scope here for our adders |
---|
3847 | Adder adders[rows]; |
---|
3848 | // read in the matrix |
---|
3849 | ... |
---|
3850 | for (r=0; r<rows; ++r) { |
---|
3851 | // tasks are initialized on this thread |
---|
3852 | Adders[r] = {matrix[r], cols, subtotals[r]}; |
---|
3853 | Adders[r](); // spawn thread and begin execution |
---|
3854 | } |
---|
3855 | } // adders go out of scope; block here until they all finish |
---|
3856 | total += subtotals[r]; |
---|
3857 | printf(.total is %d\n., total); |
---|
3858 | } |
---|
3859 | \end{cfa} |
---|
3860 | |
---|
3861 | \subsection{Cooperative Scheduling} |
---|
3862 | |
---|
3863 | Tasks in \CFA are cooperatively scheduled, meaning that a task will not be interrupted by another task, except at specific yield points. |
---|
3864 | In Listing 31, there are no yield points, so each task runs to completion with no interruptions. |
---|
3865 | 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. |
---|
3866 | 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. |
---|
3867 | For example, the code below defines a monitor that maintains a generic list. |
---|
3868 | 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. |
---|
3869 | 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. |
---|
3870 | |
---|
3871 | \begin{cfa} |
---|
3872 | // type T is used as a generic type for all definitions inside |
---|
3873 | // the curly brackets |
---|
3874 | |
---|
3875 | generic(type T) { |
---|
3876 | type Channel = monitor { |
---|
3877 | List(T) list; // list is a simple generic list type |
---|
3878 | }; |
---|
3879 | |
---|
3880 | T pop(mutex &Channel(T) ch) { |
---|
3881 | if (ch.list.empty()) { |
---|
3882 | // yield until push is called for this channel |
---|
3883 | yield(push); |
---|
3884 | } |
---|
3885 | return ch.list.pop(); |
---|
3886 | } |
---|
3887 | |
---|
3888 | void push(mutex &Channel(T)ch, T val) { |
---|
3889 | if (ch.list.full()) { |
---|
3890 | // yield until pop is called for this channel |
---|
3891 | yield(pop); |
---|
3892 | } |
---|
3893 | ch.list.push(val); |
---|
3894 | } |
---|
3895 | } |
---|
3896 | \end{cfa} |
---|
3897 | |
---|
3898 | A task can also yield indefinitely by calling yield with no arguments. |
---|
3899 | This will tell the scheduler to yield this task until it is resumed by some other task. |
---|
3900 | A task can resume another task by using its functional call operator. |
---|
3901 | The code below shows a simple ping-pong example, where two tasks yield back and forth to each other using these methods. |
---|
3902 | |
---|
3903 | \begin{cfa} |
---|
3904 | type Ping = task { |
---|
3905 | Pong *partner; |
---|
3906 | }; |
---|
3907 | |
---|
3908 | void ?{}(Ping &p, Pong *partner = 0) { |
---|
3909 | p.partner = partner; |
---|
3910 | } |
---|
3911 | |
---|
3912 | void ?()(Ping &p) { |
---|
3913 | for(;;) { // loop forever |
---|
3914 | printf(.ping\n.); |
---|
3915 | partner(); // resumes the partner task |
---|
3916 | yield(); // yields this task |
---|
3917 | } |
---|
3918 | } |
---|
3919 | |
---|
3920 | type Pong = task { |
---|
3921 | Ping *partner; |
---|
3922 | }; |
---|
3923 | |
---|
3924 | void ?{}(Pong &p, Ping *partner = 0) { |
---|
3925 | p.partner = partner; |
---|
3926 | } |
---|
3927 | |
---|
3928 | void ?()(Pong &p) { |
---|
3929 | for(;;) { // loop forever |
---|
3930 | yield(); // yields this task |
---|
3931 | printf(.pong/n.); |
---|
3932 | partner(); // resumes the partner task |
---|
3933 | } |
---|
3934 | } |
---|
3935 | |
---|
3936 | void main() { |
---|
3937 | Ping ping; // allocate ping |
---|
3938 | Pong pong{ping}; // allocate, initialize, and start pong |
---|
3939 | Ping{pong}; // initialize and start ping |
---|
3940 | } |
---|
3941 | \end{cfa} |
---|
3942 | |
---|
3943 | The same functionality can be accomplished by providing functions to be called by the partner task. |
---|
3944 | \begin{cfa} |
---|
3945 | type Pingpong = task { |
---|
3946 | String msg; |
---|
3947 | Pingpong *partner; |
---|
3948 | }; |
---|
3949 | |
---|
3950 | void ?{}(Pingpong &p, String msg, Pingpong *partner = 0) { |
---|
3951 | p.msg = msg; |
---|
3952 | p.partner = partner; |
---|
3953 | } |
---|
3954 | |
---|
3955 | void ?()(Pingpong &p) { |
---|
3956 | for(;;) { |
---|
3957 | yield(go); |
---|
3958 | } |
---|
3959 | } |
---|
3960 | |
---|
3961 | void go(Pingpong &p) { |
---|
3962 | print(.%(p.msg)\n.); |
---|
3963 | go(p.partner); |
---|
3964 | } |
---|
3965 | |
---|
3966 | void main() { |
---|
3967 | Pingpong ping = {.ping.}; |
---|
3968 | Pingpong pong = {.pong., ping}; |
---|
3969 | ping.partner = pong; |
---|
3970 | go(ping); |
---|
3971 | } |
---|
3972 | \end{cfa} |
---|
3973 | \end{comment} |
---|
3974 | |
---|
3975 | |
---|
3976 | \begin{comment} |
---|
3977 | \section{Modules and Packages } |
---|
3978 | |
---|
3979 | High-level encapsulation is useful for organizing code into reusable units, and accelerating compilation speed. |
---|
3980 | \CFA provides a convenient mechanism for creating, building and sharing groups of functionality that enhances productivity and improves compile time. |
---|
3981 | |
---|
3982 | There are two levels of encapsulation in \CFA, module and package. |
---|
3983 | A module is a logical grouping of functionality that can be easily pulled into another project, much like a module in \Index*{Python} or a package in \Index*{Go}. |
---|
3984 | A module forms a namespace to limit the visibility and prevent naming conflicts of variables. |
---|
3985 | Furthermore, a module is an independent translation unit, which can be compiled separately to accelerate the compilation speed. |
---|
3986 | |
---|
3987 | A package is a physical grouping of one or more modules that is used for code distribution and version management. |
---|
3988 | Package is also the level of granularity at which dependences are managed. |
---|
3989 | A package is similar to the Crate in \Index*{Rust}. |
---|
3990 | |
---|
3991 | |
---|
3992 | \subsection{No Declarations, No Header Files} |
---|
3993 | |
---|
3994 | In C and \Index*[C++]{\CC{}}, it is necessary to declare or define every global variable, global function, and type before it is used in each file. |
---|
3995 | Header files and a preprocessor are normally used to avoid repeating code. |
---|
3996 | Thus, many variables, functions, and types are described twice, which exposes an opportunity for errors and causes additional maintenance work. |
---|
3997 | Instead of following this model, the \CFA tools can extract all of the same information from the code automatically. |
---|
3998 | 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. |
---|
3999 | 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. |
---|
4000 | This seems like a minor change, but according to (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering), this simple change can cause massive reductions in compile time. |
---|
4001 | |
---|
4002 | In \CFA, multiple definitions are not necessary. |
---|
4003 | Within a module, all of the module's global definitions are visible throughout the module. |
---|
4004 | For example, the following code compiles, even though ©isOdd© was not declared before being called: |
---|
4005 | \begin{cfa} |
---|
4006 | bool isEven(unsigned int x) { |
---|
4007 | if (x == 0) return true; |
---|
4008 | else return !isOdd(x); |
---|
4009 | } |
---|
4010 | |
---|
4011 | bool isOdd(unsigned int x) { |
---|
4012 | if (x == 1) return true; |
---|
4013 | else return !isEven(x - 2); |
---|
4014 | } |
---|
4015 | \end{cfa} |
---|
4016 | |
---|
4017 | Header files in C are used to expose the declarations from a library, so that they can be used externally. |
---|
4018 | With \CFA, this functionality is replaced with module exports, discussed below. |
---|
4019 | 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. |
---|
4020 | |
---|
4021 | 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). |
---|
4022 | |
---|
4023 | |
---|
4024 | \subsection{Modules} |
---|
4025 | |
---|
4026 | 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. |
---|
4027 | These modules can then be easily shared and reused in multiple projects. |
---|
4028 | As modules are intended to be distributed for reuse, they should generally have stable, well-defined interfaces. |
---|
4029 | |
---|
4030 | \CFA adds the following keywords to express the module systems: module, export, import, as. |
---|
4031 | |
---|
4032 | |
---|
4033 | \subsubsection{Module Declaration} |
---|
4034 | |
---|
4035 | The syntax to declare a module is module moduleName;. |
---|
4036 | |
---|
4037 | The module declaration must be at the beginning of a file, and each file can only belong to one module. |
---|
4038 | If there is no module declaration at the beginning of a file, the file belongs to the global module. |
---|
4039 | A module can span several files. |
---|
4040 | By convention, a module and the files belonging to the module have additional mapping relationship which is described in the Do-Lang Tooling documentation. |
---|
4041 | |
---|
4042 | The moduleName follows the same rules of a variable name, except that it can use slash "/" to indicate the module/sub-module relationship. |
---|
4043 | For example, container/vector is a valid module name, where container is the parent module name, and vector is the sub-module under container. |
---|
4044 | |
---|
4045 | 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. |
---|
4046 | A method, a global variable or a type can be declared as a module interface. |
---|
4047 | Types defined in a module and referenced by an exported function or a variable must be exported, too. |
---|
4048 | |
---|
4049 | The following code is a simple module declaration example. |
---|
4050 | \begin{cfa} |
---|
4051 | module M; |
---|
4052 | |
---|
4053 | //visible outside module M |
---|
4054 | |
---|
4055 | export int f(int i) { return i + 1; } |
---|
4056 | export double aCounter; |
---|
4057 | |
---|
4058 | //not visible outside module M |
---|
4059 | |
---|
4060 | int g(int i) { return i - 1; } |
---|
4061 | |
---|
4062 | double bCounter; |
---|
4063 | \end{cfa} |
---|
4064 | |
---|
4065 | export module moduleName; can be use to re-export all the visible (exported) names in moduleName from the current module. |
---|
4066 | |
---|
4067 | |
---|
4068 | \subsubsection{Module Import} |
---|
4069 | |
---|
4070 | The syntax to import a module is import moduleName; or import moduleName as anotherName;. |
---|
4071 | One package cannot be imported with both of the two types of syntax in one file. |
---|
4072 | A package imported in one file will only be visible in this file. |
---|
4073 | For example, two files, A and B belong to the same module. |
---|
4074 | If file A imports another module, M, the exported names in M are not visible in file B. |
---|
4075 | |
---|
4076 | All of the exported names are visible in the file that imports the module. |
---|
4077 | The exported names can be accessed within a namespace based on the module name in the first syntax (ex moduleName.foo). |
---|
4078 | 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(...);). |
---|
4079 | 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. |
---|
4080 | Conflicts in namespaces will be reported by the compiler. |
---|
4081 | The second method can be used to solve conflicting name problems. |
---|
4082 | The following code snippets show the two situations. |
---|
4083 | |
---|
4084 | \begin{cfa} |
---|
4085 | module util/counter; |
---|
4086 | export int f(int i) { return i+1; } |
---|
4087 | |
---|
4088 | import util/counter; |
---|
4089 | |
---|
4090 | int main() { |
---|
4091 | return counter.f(200); // f() from the package counter |
---|
4092 | } |
---|
4093 | |
---|
4094 | import util/counter as ct; |
---|
4095 | int main() { |
---|
4096 | return ct.f(200); // f() from the package counter |
---|
4097 | } |
---|
4098 | \end{cfa} |
---|
4099 | |
---|
4100 | |
---|
4101 | 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. |
---|
4102 | |
---|
4103 | \begin{cfa} |
---|
4104 | module M1; |
---|
4105 | export int f(int i) { return i+1;} // visible outside |
---|
4106 | |
---|
4107 | int g(int i) { return i-1;} // not visible outside |
---|
4108 | |
---|
4109 | module M2; |
---|
4110 | int f(int i) { return i * 2; } // not visible outside |
---|
4111 | export int g(int g) { return i / 2; } // visible outside |
---|
4112 | |
---|
4113 | import M1 as .; |
---|
4114 | |
---|
4115 | import M2 as .; |
---|
4116 | |
---|
4117 | |
---|
4118 | int main() { |
---|
4119 | return f(3) + g(4); //f() from M1 and g() from M2; |
---|
4120 | } |
---|
4121 | \end{cfa} |
---|
4122 | |
---|
4123 | |
---|
4124 | \subsubsection{Sub-Module and Module Aggregation} |
---|
4125 | |
---|
4126 | Several modules can be organized in a parent module and sub-modules relationship. |
---|
4127 | The sub-module names are based on hierarchical naming, and use slash, "/", to indicate the relationship. |
---|
4128 | For example, std/vector and std/io are sub-modules of module std. |
---|
4129 | 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 |
---|
4130 | not implicitly exported in the parent module. |
---|
4131 | |
---|
4132 | Aggregation is a mechanism to support components and simplified importing. |
---|
4133 | The mechanism is not based on naming but based on manual declaration. |
---|
4134 | For example, the following is the aggregated sequence module. |
---|
4135 | The export {...} is syntactic sugar for many lines of export module aModule;. |
---|
4136 | If an aggregated module is imported, all the included modules in the aggregation are imported. |
---|
4137 | |
---|
4138 | \begin{cfa} |
---|
4139 | module std/sequence; |
---|
4140 | |
---|
4141 | export { |
---|
4142 | module std/vector; |
---|
4143 | module std/list; |
---|
4144 | module std/array; |
---|
4145 | module std/deque; |
---|
4146 | module std/forward_list; |
---|
4147 | module std/queue; |
---|
4148 | module std/stack; |
---|
4149 | }; |
---|
4150 | \end{cfa} |
---|
4151 | |
---|
4152 | After importing the aggregated module, each individual name is still contained in the original name space. |
---|
4153 | 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. |
---|
4154 | |
---|
4155 | |
---|
4156 | \subsubsection{Import from Repository} |
---|
4157 | |
---|
4158 | 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). |
---|
4159 | The tools also support retrieving modules of a package from external repositories. |
---|
4160 | See Listing 40: Package directory structure |
---|
4161 | |
---|
4162 | |
---|
4163 | \subsubsection{Package Import} |
---|
4164 | |
---|
4165 | 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. |
---|
4166 | 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; |
---|
4167 | or 2) Adding the package dependence into the current project's Do.prj. |
---|
4168 | More details about locating a module in a package are explained in the next section. |
---|
4169 | |
---|
4170 | |
---|
4171 | \subsubsection{Package Versioning} |
---|
4172 | |
---|
4173 | A package must have a version number. |
---|
4174 | The version number is a string. |
---|
4175 | For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers. |
---|
4176 | By convention, a package is stored in a directory named packageName-packageVersion. |
---|
4177 | For example, the util package with version 1.1 is stored in a directory named util-1.1. |
---|
4178 | |
---|
4179 | The project description file can optionally specify the version of the package used in the current project. |
---|
4180 | 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. |
---|
4181 | 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. |
---|
4182 | |
---|
4183 | |
---|
4184 | \subsection{Module and Package Organization} |
---|
4185 | |
---|
4186 | \CFA has two level of encapsulations, module and package. |
---|
4187 | This section explains the object model of modules, packages and other language concepts. |
---|
4188 | 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. |
---|
4189 | |
---|
4190 | |
---|
4191 | \subsubsection{Object Model} |
---|
4192 | |
---|
4193 | There are several concepts in Do. |
---|
4194 | \begin{itemize} |
---|
4195 | \item |
---|
4196 | File: a \CFA source file |
---|
4197 | \item |
---|
4198 | Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside |
---|
4199 | \item |
---|
4200 | Package: a container to organize modules for distribution; It has attributes like name, author, |
---|
4201 | version, dependences, etc. |
---|
4202 | \item |
---|
4203 | Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc. |
---|
4204 | \end{itemize} |
---|
4205 | |
---|
4206 | The following rules summarize the object model of all the above concepts: |
---|
4207 | \begin{itemize} |
---|
4208 | \item |
---|
4209 | A module contains one or more files |
---|
4210 | \begin{itemize} |
---|
4211 | \item |
---|
4212 | One file can only belong to one module |
---|
4213 | \item |
---|
4214 | A module has its name and interfaces exported |
---|
4215 | \item |
---|
4216 | A file without a module declaration at the beginning belongs to the global module |
---|
4217 | \item |
---|
4218 | \end{itemize} |
---|
4219 | |
---|
4220 | \item |
---|
4221 | A package contains one or more modules |
---|
4222 | \begin{itemize} |
---|
4223 | \item |
---|
4224 | A package has additional meta info described in Do.prj file |
---|
4225 | \item |
---|
4226 | A package may be dependent on other packages. |
---|
4227 | \end{itemize} |
---|
4228 | |
---|
4229 | \item |
---|
4230 | A project contains one or more modules in its source code |
---|
4231 | \begin{itemize} |
---|
4232 | \item |
---|
4233 | A project has additional meta info described in Do.prj file |
---|
4234 | \item |
---|
4235 | A project may be dependent on other packages |
---|
4236 | \item |
---|
4237 | A project can be transformed into a package for distribution |
---|
4238 | \item |
---|
4239 | A project can generate one or more executable binaries |
---|
4240 | \end{itemize} |
---|
4241 | \end{itemize} |
---|
4242 | |
---|
4243 | |
---|
4244 | \subsubsection{Module File Organization} |
---|
4245 | |
---|
4246 | The rules of this section are the conventions to organize module files in one package. |
---|
4247 | |
---|
4248 | The file location of a module in a package must match the module/submodule naming hierarchy. |
---|
4249 | The names separated by slash "/" must match the directory levels. |
---|
4250 | If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory. |
---|
4251 | The file can be put inside its parent module's sub-directory with the sub module's name as the file name. |
---|
4252 | |
---|
4253 | Here is an example of a package, util. |
---|
4254 | \begin{cfa} |
---|
4255 | + util |
---|
4256 | Do.prj #package description file |
---|
4257 | heap.do #Case 1: module heap; |
---|
4258 | list.do #Case 1: mdoule list; |
---|
4259 | ring.do #Case 1: module ring; |
---|
4260 | + string #Case 2 |
---|
4261 | impl1.do #module string; |
---|
4262 | + std |
---|
4263 | vector.do |
---|
4264 | list.do |
---|
4265 | + array #Case 3 |
---|
4266 | array1.do #module std/array; |
---|
4267 | array2.do #module std/array; |
---|
4268 | sequence.do #Case 4, module std/sequence; |
---|
4269 | test.do #Case 5 |
---|
4270 | \end{cfa} |
---|
4271 | |
---|
4272 | \begin{itemize} |
---|
4273 | \item |
---|
4274 | Case 1: Each individual file implements a module |
---|
4275 | \item |
---|
4276 | Case 2: Put the implementation of a module under the sub-directory, but there is only one file |
---|
4277 | \item |
---|
4278 | Case 3: Put the implementation of a module under the sub-directory; There are several files to |
---|
4279 | implement one module |
---|
4280 | \item |
---|
4281 | Case 4: One file to express one aggregation |
---|
4282 | \item |
---|
4283 | Case 5: The file does not belong to any module; It is used for testing purpose |
---|
4284 | \end{itemize} |
---|
4285 | |
---|
4286 | The example only uses source code, ".do" files, to show the module file organization. |
---|
4287 | Other module packaging formats, like binary, must also follow the same rules. |
---|
4288 | |
---|
4289 | |
---|
4290 | \subsection{Module File Format} |
---|
4291 | |
---|
4292 | \CFA supports different types of module file formats. |
---|
4293 | |
---|
4294 | \begin{itemize} |
---|
4295 | \item |
---|
4296 | Pure source code format: The files should be organized following the previous section's definition. |
---|
4297 | \item |
---|
4298 | IR format (TBD): The \CFA compiler IR format, similar to the source code format |
---|
4299 | \item |
---|
4300 | Binary format, including ".a" static library or ".so" dynamic linkage library |
---|
4301 | \begin{itemize} |
---|
4302 | \item |
---|
4303 | The file's name must match the right level's module name defined in the previous section |
---|
4304 | \item |
---|
4305 | E.g. "util.so" includes all modules for the package util. |
---|
4306 | \item |
---|
4307 | E.g. "string.so" under the package directory to include files belonging to "module string;" |
---|
4308 | \end{itemize} |
---|
4309 | \item. |
---|
4310 | Archive format |
---|
4311 | \begin{itemize} |
---|
4312 | \item |
---|
4313 | The archive is named as ".dar", and is a zip archive of the source code or the binary for a package |
---|
4314 | \item |
---|
4315 | E.g. "util.dar" is the whole package for util package including the package direction file |
---|
4316 | \end{itemize} |
---|
4317 | \item |
---|
4318 | Hybrid format |
---|
4319 | \begin{itemize} |
---|
4320 | \item |
---|
4321 | A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format |
---|
4322 | \item |
---|
4323 | The only limitation is that the names of the files must match the module location names defined in previous section |
---|
4324 | \end{itemize} |
---|
4325 | \end{itemize} |
---|
4326 | Package and Module Locating and the \CFA Language Tooling documentation for more details. |
---|
4327 | |
---|
4328 | |
---|
4329 | \subsection{Packages} |
---|
4330 | |
---|
4331 | A package is synonymous with a library in other languages. |
---|
4332 | The intent of the package level encapsulation is to facilitate code distribution, version control, and dependence management. |
---|
4333 | A package is a physical grouping of one or more modules in a directory (an archive file for a directory). |
---|
4334 | 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. |
---|
4335 | |
---|
4336 | |
---|
4337 | \subsubsection{Package Definition} |
---|
4338 | |
---|
4339 | A package is defined by putting a project description file, Do.prj, with one or more modules into a directory. |
---|
4340 | This project description file contains the package's meta data, including package name, author, version, dependences, etc. |
---|
4341 | It should be in the root of the package directory. |
---|
4342 | |
---|
4343 | The modules in the package could be either source code, or compiled binary format. |
---|
4344 | The location of the module files should follow the module name's path. |
---|
4345 | |
---|
4346 | Here is a simple example of the directory structure of a package, core. |
---|
4347 | It contains a module std and several sub-modules under std. |
---|
4348 | \begin{cfa} |
---|
4349 | + core |
---|
4350 | Do.prj |
---|
4351 | + std |
---|
4352 | + io |
---|
4353 | file.do # module std/io/file; |
---|
4354 | network.do #module std/io/network; |
---|
4355 | + container |
---|
4356 | vector.do #module std/container/vector; |
---|
4357 | list.do #module std/container/list; |
---|
4358 | \end{cfa} |
---|
4359 | |
---|
4360 | |
---|
4361 | \subsubsection{Package Import} |
---|
4362 | |
---|
4363 | 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. |
---|
4364 | 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. |
---|
4365 | More details about locating a module in a package are explained in the next section. |
---|
4366 | |
---|
4367 | |
---|
4368 | \subsubsection{Package Versioning} |
---|
4369 | |
---|
4370 | A package must have a version number. |
---|
4371 | The version number is a string. |
---|
4372 | For example "1.0", "1.a", "A1", and "1ec5fab753eb979d3886a491845b8ae152d58c8f" are all valid version numbers. |
---|
4373 | By convention, a package is stored in a directory named packageName-packageVersion. |
---|
4374 | For example, the util package with version 1.1 is stored in a directory named util-1.1. |
---|
4375 | |
---|
4376 | The project description file can optionally specify the version of the package used in the current project. |
---|
4377 | 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. |
---|
4378 | 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. |
---|
4379 | |
---|
4380 | |
---|
4381 | \subsection{Module and Package Organization} |
---|
4382 | |
---|
4383 | \CFA has two level of encapsulations, module and package. |
---|
4384 | This section explains the object model of modules, packages and other language concepts. |
---|
4385 | 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. |
---|
4386 | |
---|
4387 | |
---|
4388 | \subsubsection{Object Model} |
---|
4389 | |
---|
4390 | There are several concepts in Do. |
---|
4391 | \begin{itemize} |
---|
4392 | \item |
---|
4393 | File: a \CFA source file |
---|
4394 | \item |
---|
4395 | Module: a container to organize a set of related types and methods; It has a module name, and several interfaces visible from outside |
---|
4396 | \item |
---|
4397 | Package: a container to organize modules for distribution; It has attributes like name, author, version, dependences, etc. |
---|
4398 | \item |
---|
4399 | Project: a working set for a \CFA project; It has attributes like name, author, version, dependences, etc. |
---|
4400 | \end{itemize} |
---|
4401 | |
---|
4402 | The following rules summarize the object model of all the above concepts: |
---|
4403 | \begin{itemize} |
---|
4404 | \item |
---|
4405 | A module contains one or more files |
---|
4406 | \begin{itemize} |
---|
4407 | \item |
---|
4408 | One file can only belong to one module |
---|
4409 | \item |
---|
4410 | A module has its name and interfaces exported |
---|
4411 | \item |
---|
4412 | A file without a module declaration at the beginning belongs to the global module |
---|
4413 | \end{itemize} |
---|
4414 | \item |
---|
4415 | A package contains one or more modules |
---|
4416 | \begin{itemize} |
---|
4417 | \item |
---|
4418 | A package has additional meta info described in Do.prj file |
---|
4419 | \item |
---|
4420 | A package may be dependent on other packages. |
---|
4421 | \end{itemize} |
---|
4422 | \item |
---|
4423 | A project contains one or more modules in its source code |
---|
4424 | \begin{itemize} |
---|
4425 | \item |
---|
4426 | A project has additional meta info described in Do.prj file |
---|
4427 | \item |
---|
4428 | A project may be dependent on other packages |
---|
4429 | \item |
---|
4430 | A project can be transformed into a package for distribution |
---|
4431 | \item |
---|
4432 | A project can generate one or more executable binaries |
---|
4433 | \end{itemize} |
---|
4434 | \end{itemize} |
---|
4435 | |
---|
4436 | |
---|
4437 | \subsubsection{Module File Organization} |
---|
4438 | |
---|
4439 | The rules of this section are the conventions to organize module files in one package. |
---|
4440 | |
---|
4441 | The file location of a module in a package must match the module/submodule naming hierarchy. |
---|
4442 | The names separated by slash "/" must match the directory levels. |
---|
4443 | If only one file is used to implement one module, there is no need to put the module implementation file inside a sub-directory. |
---|
4444 | The file can be put inside its parent module's sub-directory with the sub module's name as the file name. |
---|
4445 | |
---|
4446 | Here is an example of a package, util. |
---|
4447 | \begin{cfa} |
---|
4448 | + util |
---|
4449 | Do.prj #package description file |
---|
4450 | heap.do #Case 1: module heap; |
---|
4451 | list.do #Case 1: mdoule list; |
---|
4452 | ring.do #Case 1: module ring; |
---|
4453 | + string #Case 2 |
---|
4454 | impl1.do #module string; |
---|
4455 | + std |
---|
4456 | vector.do |
---|
4457 | list.do |
---|
4458 | + array #Case 3 |
---|
4459 | array1.do #module std/array; |
---|
4460 | array2.do #module std/array; |
---|
4461 | sequence.do #Case 4, module std/sequence; |
---|
4462 | test.do #Case 5 |
---|
4463 | \end{cfa} |
---|
4464 | |
---|
4465 | |
---|
4466 | \begin{itemize} |
---|
4467 | \item |
---|
4468 | Case 1: Each individual file implements a module |
---|
4469 | \item |
---|
4470 | Case 2: Put the implementation of a module under the sub-directory, but there is only one file |
---|
4471 | \item |
---|
4472 | Case 3: Put the implementation of a module under the sub-directory; There are several files to implement one module |
---|
4473 | \item |
---|
4474 | Case 4: One file to express one aggregation |
---|
4475 | \item |
---|
4476 | Case 5: The file does not belong to any module; It is used for testing purpose |
---|
4477 | \end{itemize} |
---|
4478 | |
---|
4479 | The example only uses source code, ".do" files, to show the module file organization. |
---|
4480 | Other module packaging formats, like binary, must also follow the same rules. |
---|
4481 | |
---|
4482 | |
---|
4483 | \subsubsection{Module File Format} |
---|
4484 | |
---|
4485 | \CFA supports different types of module file formats. |
---|
4486 | |
---|
4487 | \begin{itemize} |
---|
4488 | \item |
---|
4489 | Pure source code format: The files should be organized following the previous section's definition. |
---|
4490 | \item |
---|
4491 | IR format (TBD): The \CFA compiler IR format, similar to the source code format |
---|
4492 | \item |
---|
4493 | Binary format, including ".a" static library or ".so" dynamic linkage library |
---|
4494 | \begin{itemize} |
---|
4495 | \item |
---|
4496 | The file's name must match the right level's module name defined in the previous section |
---|
4497 | \item |
---|
4498 | E.g. "util.so" includes all modules for the package util. |
---|
4499 | \item |
---|
4500 | E.g. "string.so" under the package directory to include files belonging to "module string;" |
---|
4501 | \end{itemize} |
---|
4502 | \item |
---|
4503 | Archive format |
---|
4504 | \begin{itemize} |
---|
4505 | \item |
---|
4506 | The archive is named as ".dar", and is a zip archive of the source code or the binary for a package |
---|
4507 | \item |
---|
4508 | E.g. "util.dar" is the whole package for util package including the package direction file |
---|
4509 | \end{itemize} |
---|
4510 | \item |
---|
4511 | Hybrid format |
---|
4512 | \begin{itemize} |
---|
4513 | \item |
---|
4514 | A package can be distributed partly in source code, partly in binary format, and/or packaged in the archive format |
---|
4515 | \item |
---|
4516 | The only limitation is that the names of the files must match the module location names defined in previous section |
---|
4517 | \end{itemize} |
---|
4518 | \end{itemize} |
---|
4519 | |
---|
4520 | |
---|
4521 | \subsection{Package and Module Locating} |
---|
4522 | |
---|
4523 | 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. |
---|
4524 | If a programmer prefers, one can directly call the compiler, docc to build the source files and create and link to static libraries. |
---|
4525 | |
---|
4526 | When a source file imports a module, the \CFA build tool and docc compiler will locate the module according to the following order: |
---|
4527 | |
---|
4528 | \begin{enumerate} |
---|
4529 | \item |
---|
4530 | This source file's directory tree, which is typically the project's src directory |
---|
4531 | \item |
---|
4532 | All of the dependent packages (in a directory or in an archive file) under the current \CFA project's pkg directory |
---|
4533 | \item |
---|
4534 | The dependent packages (in a directory or in an archive file) inside the paths defined in the DOPATH environment variable |
---|
4535 | \item |
---|
4536 | The dependent packages (in a directory or in an archive file) inside the global \CFA SDK installation's pkg directory |
---|
4537 | \item |
---|
4538 | 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 |
---|
4539 | \end{enumerate} |
---|
4540 | |
---|
4541 | The module found first in a package will shadow the modules with the same name in the later packages in the search sequence. |
---|
4542 | |
---|
4543 | |
---|
4544 | \subsubsection{Dependent Package} |
---|
4545 | |
---|
4546 | Dependent packages are those packages containing modules that the current project's source code will import from. |
---|
4547 | Dependent packages are defined implicitly or explicitly in one \CFA project. |
---|
4548 | All of the packages under the current project's pkg directory are implicitly dependent packages. |
---|
4549 | For others, the dependent packages must be defined in the project's Do.prj file. |
---|
4550 | |
---|
4551 | |
---|
4552 | \subsubsection{Package and Module Locating Example} |
---|
4553 | |
---|
4554 | \begin{cfa} |
---|
4555 | # A project's source code tree |
---|
4556 | |
---|
4557 | -------------------------------------- |
---|
4558 | |
---|
4559 | + testProject |
---|
4560 | Do.prj |
---|
4561 | + src |
---|
4562 | main.do |
---|
4563 | + pkg |
---|
4564 | + security-1.1 |
---|
4565 | Do.prj |
---|
4566 | security.do #module security |
---|
4567 | |
---|
4568 | -------------------------------------- |
---|
4569 | |
---|
4570 | # Do.prj |
---|
4571 | |
---|
4572 | -------------------------------------- |
---|
4573 | |
---|
4574 | [dependences] |
---|
4575 | std |
---|
4576 | util = "0.2" |
---|
4577 | |
---|
4578 | -------------------------------------- |
---|
4579 | |
---|
4580 | # main.do |
---|
4581 | |
---|
4582 | --------------------------------------- |
---|
4583 | |
---|
4584 | import security; |
---|
4585 | import std/vector; |
---|
4586 | import container; |
---|
4587 | |
---|
4588 | ---------------------------------------- |
---|
4589 | \end{cfa} |
---|
4590 | |
---|
4591 | |
---|
4592 | \begin{cfa} |
---|
4593 | # pkg directory's source code tree |
---|
4594 | |
---|
4595 | ----------------------------------------- |
---|
4596 | |
---|
4597 | + pkg |
---|
4598 | + std-1.0 |
---|
4599 | Do.prj |
---|
4600 | vector.do #module std/vector; |
---|
4601 | queue.do #module std/queue; |
---|
4602 | + std-1.1 |
---|
4603 | Do.prj |
---|
4604 | vector.do #module std/vector; |
---|
4605 | queue.do #module std/queue; |
---|
4606 | list.do #module std/list; |
---|
4607 | + util-0.1 |
---|
4608 | Do.prj |
---|
4609 | container.do #module container; |
---|
4610 | + security-1.0 |
---|
4611 | security.do #module security; |
---|
4612 | ------------------------------------------ |
---|
4613 | \end{cfa} |
---|
4614 | |
---|
4615 | |
---|
4616 | During the compiling of main.do file import security; |
---|
4617 | The security module appears in both the local security-1.1 package, and the global security-1.0 package. |
---|
4618 | According to the locating sequence, the local security module in security-1.1 will be used. |
---|
4619 | And because the security-1.1 package is under local's pkg directory. |
---|
4620 | No dependence description is required in the project Do.prj file. |
---|
4621 | |
---|
4622 | import std/vector; |
---|
4623 | |
---|
4624 | 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. |
---|
4625 | |
---|
4626 | import container; |
---|
4627 | |
---|
4628 | 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. |
---|
4629 | The builder tool then will try to retrieve it from the web and store it in the global pkg directory. |
---|
4630 | After that, the container module from the newly downloaded package will be used in the compilation. |
---|
4631 | \end{comment} |
---|
4632 | |
---|
4633 | |
---|
4634 | \section{Comparison with Other Languages} |
---|
4635 | |
---|
4636 | \CFA is one of many languages that attempts to improve upon C. |
---|
4637 | In developing \CFA, many other languages were consulted for ideas, constructs, and syntax. |
---|
4638 | Therefore, it is important to show how these languages each compare with Do. |
---|
4639 | In this section, \CFA is compared with what the writers of this document consider to be the closest competitors of Do: \Index*[C++]{\CC{}}, \Index*{Go}, \Index*{Rust}, and \Index*{D}. |
---|
4640 | |
---|
4641 | |
---|
4642 | \begin{comment} |
---|
4643 | \subsection[Comparing Key Features of CFA]{Comparing Key Features of \CFA} |
---|
4644 | |
---|
4645 | |
---|
4646 | {% local change to lstlising to reduce font size |
---|
4647 | |
---|
4648 | |
---|
4649 | \lstset{basicstyle=\linespread{0.9}\sf\relsize{-2}} |
---|
4650 | |
---|
4651 | |
---|
4652 | \subsubsection{Constructors and Destructors} |
---|
4653 | |
---|
4654 | \begin{flushleft} |
---|
4655 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4656 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4657 | \hline |
---|
4658 | \begin{cfa} |
---|
4659 | struct Line { |
---|
4660 | float lnth; |
---|
4661 | } |
---|
4662 | // default constructor |
---|
4663 | void ?{}( Line * l ) { |
---|
4664 | l->lnth = 0.0; |
---|
4665 | sout | "default" | endl; |
---|
4666 | } |
---|
4667 | |
---|
4668 | |
---|
4669 | // constructor with length |
---|
4670 | void ?{}( Line * l, float lnth ) { |
---|
4671 | l->lnth = lnth; |
---|
4672 | sout | "lnth" | l->lnth | endl; |
---|
4673 | |
---|
4674 | } |
---|
4675 | |
---|
4676 | // destructor |
---|
4677 | void ^?() { |
---|
4678 | sout | "destroyed" | endl; |
---|
4679 | l.lnth = 0.0; |
---|
4680 | } |
---|
4681 | |
---|
4682 | // usage |
---|
4683 | Line line1; |
---|
4684 | Line line2 = { 3.4 }; |
---|
4685 | \end{cfa} |
---|
4686 | & |
---|
4687 | \begin{lstlisting}[language=C++] |
---|
4688 | class Line { |
---|
4689 | float lnth; |
---|
4690 | |
---|
4691 | // default constructor |
---|
4692 | Line() { |
---|
4693 | cout << "default" << endl; |
---|
4694 | lnth = 0.0; |
---|
4695 | } |
---|
4696 | |
---|
4697 | |
---|
4698 | // constructor with lnth |
---|
4699 | Line( float l ) { |
---|
4700 | cout << "length " << length |
---|
4701 | << endl; |
---|
4702 | length = l; |
---|
4703 | } |
---|
4704 | |
---|
4705 | // destructor |
---|
4706 | ~Line() { |
---|
4707 | cout << "destroyed" << endl; |
---|
4708 | length = 0.0; |
---|
4709 | } |
---|
4710 | } |
---|
4711 | // usage |
---|
4712 | Line line1; |
---|
4713 | Line line2( 3.4 ); |
---|
4714 | \end{lstlisting} |
---|
4715 | & |
---|
4716 | \begin{lstlisting}[language=Golang] |
---|
4717 | type Line struct { |
---|
4718 | length float32 |
---|
4719 | } |
---|
4720 | // default constructor |
---|
4721 | func makeLine() Line { |
---|
4722 | fmt.PrintLn( "default" ) |
---|
4723 | return Line{0.0} |
---|
4724 | } |
---|
4725 | |
---|
4726 | |
---|
4727 | // constructor with length |
---|
4728 | func makeLine( length float32 ) Line { |
---|
4729 | fmt.Printf( "length %v", length ) |
---|
4730 | |
---|
4731 | return Line{length} |
---|
4732 | } |
---|
4733 | |
---|
4734 | // no destructor |
---|
4735 | |
---|
4736 | |
---|
4737 | |
---|
4738 | |
---|
4739 | |
---|
4740 | // usage |
---|
4741 | line1 := makeLine() |
---|
4742 | line2 := makeLine( 3.4 ) |
---|
4743 | \end{lstlisting} |
---|
4744 | & |
---|
4745 | \begin{cfa} |
---|
4746 | struct Line { |
---|
4747 | length: f32 |
---|
4748 | } |
---|
4749 | // default constructor |
---|
4750 | impl Default for Line { |
---|
4751 | fn default () -> Line { |
---|
4752 | println!( "default" ); |
---|
4753 | Line{ length: 0.0 } |
---|
4754 | } |
---|
4755 | } |
---|
4756 | // constructor with length |
---|
4757 | impl Line { |
---|
4758 | fn make( len: f32 ) -> Line { |
---|
4759 | println!( "length: {}", len ); |
---|
4760 | Line{ length: len } |
---|
4761 | } |
---|
4762 | } |
---|
4763 | // destructor |
---|
4764 | impl Drop for Line { |
---|
4765 | fn drop( &mut self ) { |
---|
4766 | self.length = 0.0 |
---|
4767 | } |
---|
4768 | } |
---|
4769 | // usage |
---|
4770 | let line1:Line = Default::default(); |
---|
4771 | Line line2( 3.4 ); |
---|
4772 | \end{cfa} |
---|
4773 | \end{tabular} |
---|
4774 | \end{flushleft} |
---|
4775 | |
---|
4776 | |
---|
4777 | \subsubsection{Operator Overloading} |
---|
4778 | |
---|
4779 | \begin{flushleft} |
---|
4780 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4781 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4782 | \hline |
---|
4783 | \begin{cfa} |
---|
4784 | struct Cpx { |
---|
4785 | double re, im; |
---|
4786 | }; |
---|
4787 | // overload addition operator |
---|
4788 | Cpx ?+?( Cpx l, const Cpx r ) { |
---|
4789 | return (Cpx){l.re+l.im, l.im+r.im}; |
---|
4790 | } |
---|
4791 | Cpx a, b, c; |
---|
4792 | c = a + b; |
---|
4793 | \end{cfa} |
---|
4794 | & |
---|
4795 | \begin{cfa} |
---|
4796 | struct Cpx { |
---|
4797 | double re, im; |
---|
4798 | }; |
---|
4799 | // overload addition operator |
---|
4800 | Cpx operator+( Cpx l, const Cpx r ) { |
---|
4801 | return (Cpx){l.re+l.im, l.im+r.im}; |
---|
4802 | } |
---|
4803 | Cpx a, b, c; |
---|
4804 | c = a + b; |
---|
4805 | \end{cfa} |
---|
4806 | & |
---|
4807 | \begin{cfa} |
---|
4808 | // no operator overloading |
---|
4809 | |
---|
4810 | |
---|
4811 | |
---|
4812 | |
---|
4813 | |
---|
4814 | |
---|
4815 | |
---|
4816 | \end{cfa} |
---|
4817 | & |
---|
4818 | \begin{cfa} |
---|
4819 | struct Cpx { |
---|
4820 | re: f32, |
---|
4821 | im: f32 |
---|
4822 | } |
---|
4823 | // overload addition operator |
---|
4824 | impl Add for Cpx { |
---|
4825 | type Output = Cpx |
---|
4826 | fn add(self, r: Cpx) -> Cpx { |
---|
4827 | let mut res = Cpx{re: 0.0, im: 0.0}; |
---|
4828 | res.re = self.re + r.re; |
---|
4829 | res.im = self.im + r.im; |
---|
4830 | return res |
---|
4831 | } |
---|
4832 | } |
---|
4833 | let (a, b, mut c) = ...; |
---|
4834 | c = a + b |
---|
4835 | \end{cfa} |
---|
4836 | \end{tabular} |
---|
4837 | \end{flushleft} |
---|
4838 | |
---|
4839 | |
---|
4840 | \subsubsection{Calling C Functions} |
---|
4841 | |
---|
4842 | \begin{flushleft} |
---|
4843 | \begin{tabular}{@{}l|l|l@{}} |
---|
4844 | \multicolumn{1}{c|}{\textbf{\CFA/\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4845 | \hline |
---|
4846 | \begin{cfa}[boxpos=t] |
---|
4847 | extern "C" { |
---|
4848 | #include <sys/types.h> |
---|
4849 | #include <sys/stat.h> |
---|
4850 | #include <unistd.h> |
---|
4851 | } |
---|
4852 | size_t fileSize( const char *path ) { |
---|
4853 | struct stat s; |
---|
4854 | stat(path, &s); |
---|
4855 | return s.st_size; |
---|
4856 | } |
---|
4857 | \end{cfa} |
---|
4858 | & |
---|
4859 | \begin{cfa}[boxpos=t] |
---|
4860 | /* |
---|
4861 | #cgo |
---|
4862 | #include <sys/types.h> |
---|
4863 | #include <sys/stat.h> |
---|
4864 | #include <unistd.h> |
---|
4865 | */ |
---|
4866 | import "C" |
---|
4867 | import "unsafe" |
---|
4868 | |
---|
4869 | func fileSize(path string) C.size_t { |
---|
4870 | var buf C.struct_stat |
---|
4871 | c_string := C.CString(path) |
---|
4872 | C.stat(p, &buf) |
---|
4873 | C.free(unsafe.Pointer(c_string)) |
---|
4874 | return buf._st_size |
---|
4875 | } |
---|
4876 | \end{cfa} |
---|
4877 | & |
---|
4878 | \begin{cfa}[boxpos=t] |
---|
4879 | use libc::{c_int, size_t}; |
---|
4880 | // translated from sys/stat.h |
---|
4881 | #[repr(C)] |
---|
4882 | struct stat_t { |
---|
4883 | ... |
---|
4884 | st_size: size_t, |
---|
4885 | ... |
---|
4886 | } |
---|
4887 | #[link(name = "libc")] |
---|
4888 | extern { |
---|
4889 | fn stat(path: *const u8, |
---|
4890 | buf: *mut stat_t) -> c_int; |
---|
4891 | } |
---|
4892 | fn fileSize(path: *const u8) -> size_t |
---|
4893 | { |
---|
4894 | unsafe { |
---|
4895 | let mut buf: stat_t = uninit(); |
---|
4896 | stat(path, &mut buf); |
---|
4897 | buf.st_size |
---|
4898 | } |
---|
4899 | } |
---|
4900 | \end{cfa} |
---|
4901 | \end{tabular} |
---|
4902 | \end{flushleft} |
---|
4903 | |
---|
4904 | |
---|
4905 | \subsubsection{Generic Functions} |
---|
4906 | |
---|
4907 | \begin{flushleft} |
---|
4908 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
4909 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
4910 | \hline |
---|
4911 | \begin{cfa} |
---|
4912 | generic(type T, type N | |
---|
4913 | { int ?<?(N, N); }) |
---|
4914 | T *maximize(N (*f)(const T&), |
---|
4915 | int n, T *a) { |
---|
4916 | T *bestX = NULL; |
---|
4917 | N bestN; |
---|
4918 | for (int i = 0; i < n; i++) { |
---|
4919 | N curN = f(a[i]); |
---|
4920 | if (bestX == NULL || |
---|
4921 | curN > bestN) { |
---|
4922 | bestX = &a[i]; bestN = curN; |
---|
4923 | } |
---|
4924 | } |
---|
4925 | return bestX; |
---|
4926 | } |
---|
4927 | |
---|
4928 | string *longest(int n, string *p) |
---|
4929 | { |
---|
4930 | return maximize(length, n, p); |
---|
4931 | } |
---|
4932 | \end{cfa} |
---|
4933 | & |
---|
4934 | \begin{cfa} |
---|
4935 | template<typename T, typename F> |
---|
4936 | T *maximize(const F &f, |
---|
4937 | int n, T *a) { |
---|
4938 | typedef decltype(f(a[0])) N; |
---|
4939 | T *bestX = NULL; |
---|
4940 | N bestN; |
---|
4941 | for (int i = 0; i < n; i++) { |
---|
4942 | N curN = f(a[i]); |
---|
4943 | if (bestX == NULL || curN > bestN) |
---|
4944 | { |
---|
4945 | bestX = &a[i]; bestN = curN; |
---|
4946 | } |
---|
4947 | } |
---|
4948 | return bestX; |
---|
4949 | } |
---|
4950 | |
---|
4951 | string *longest(int n, string *p) { |
---|
4952 | return maximize( |
---|
4953 | [](const string &s) { |
---|
4954 | return s.length(); |
---|
4955 | }, n, p); |
---|
4956 | } |
---|
4957 | \end{cfa} |
---|
4958 | & |
---|
4959 | \begin{cfa} |
---|
4960 | // Go does not support generics! |
---|
4961 | func maximize( |
---|
4962 | gt func(interface{}, interface{}) bool, |
---|
4963 | f func(interface{}) interface{}, |
---|
4964 | a []interface{}) interface{} { |
---|
4965 | var bestX interface{} = nil |
---|
4966 | var bestN interface{} = nil |
---|
4967 | for _, x := range a { |
---|
4968 | curN := f(x) |
---|
4969 | if bestX == nil || gt(curN, bestN) |
---|
4970 | { |
---|
4971 | bestN = curN |
---|
4972 | bestX = x |
---|
4973 | } |
---|
4974 | } |
---|
4975 | return bestX |
---|
4976 | } |
---|
4977 | |
---|
4978 | func longest( |
---|
4979 | a []interface{}) interface{} { |
---|
4980 | return maximize( |
---|
4981 | func(a, b interface{}) bool { |
---|
4982 | return a.(int) > b.(int) }, |
---|
4983 | func(s interface{}) interface{} { |
---|
4984 | return len(s.(string)) }, |
---|
4985 | a).(string) |
---|
4986 | } |
---|
4987 | \end{cfa} |
---|
4988 | & |
---|
4989 | \begin{cfa} |
---|
4990 | use std::cmp::Ordering; |
---|
4991 | |
---|
4992 | fn maximize<N: Ord + Copy, T, F: |
---|
4993 | Fn(&T) -> N>(f: F, a: &Vec<T>) -> |
---|
4994 | Option<&T> { |
---|
4995 | let mut best_x: Option<&T> = None; |
---|
4996 | let mut best_n: Option<N> = None; |
---|
4997 | for x in a { |
---|
4998 | let n = f(x); |
---|
4999 | if (match best_n { None => true, |
---|
5000 | Some(bn) => |
---|
5001 | n.cmp(&bn) == Ordering::Greater }) |
---|
5002 | { |
---|
5003 | best_x = Some(x); |
---|
5004 | best_n = Some(n); |
---|
5005 | } |
---|
5006 | } |
---|
5007 | return best_x |
---|
5008 | } |
---|
5009 | |
---|
5010 | fn longest(a: &Vec<String>) -> |
---|
5011 | Option<&String> { |
---|
5012 | return |
---|
5013 | maximize(|x: &String| x.len(), a) |
---|
5014 | } |
---|
5015 | \end{cfa} |
---|
5016 | \end{tabular} |
---|
5017 | \end{flushleft} |
---|
5018 | |
---|
5019 | |
---|
5020 | \subsubsection{Modules / Packages} |
---|
5021 | |
---|
5022 | \begin{cfa} |
---|
5023 | \CFA |
---|
5024 | \CC |
---|
5025 | |
---|
5026 | |
---|
5027 | module example/M; |
---|
5028 | |
---|
5029 | export int inc(int val) { |
---|
5030 | return val + 1; |
---|
5031 | } |
---|
5032 | |
---|
5033 | |
---|
5034 | |
---|
5035 | |
---|
5036 | -------------------------------------- |
---|
5037 | //Use the module in another file |
---|
5038 | import example/M; |
---|
5039 | int main() { |
---|
5040 | print(M.inc(100)); |
---|
5041 | return 0; |
---|
5042 | } |
---|
5043 | // Using \CC17 module proposal |
---|
5044 | |
---|
5045 | module example.M; |
---|
5046 | |
---|
5047 | export { |
---|
5048 | int inc(int val); |
---|
5049 | } |
---|
5050 | |
---|
5051 | int inc(inv val) { |
---|
5052 | return val + 1; |
---|
5053 | } |
---|
5054 | -------------------------------------- |
---|
5055 | // Use the module in another file |
---|
5056 | import example.M; |
---|
5057 | int main() { |
---|
5058 | cout << inc(100) << endl; |
---|
5059 | return 0; |
---|
5060 | } |
---|
5061 | |
---|
5062 | Go |
---|
5063 | Rust |
---|
5064 | package example/M; |
---|
5065 | |
---|
5066 | func Inc(val int32) int32 { |
---|
5067 | // Capitalization indicates exported |
---|
5068 | return val + 100 |
---|
5069 | } |
---|
5070 | |
---|
5071 | |
---|
5072 | -------------------------------------- |
---|
5073 | //Use the package in another file |
---|
5074 | package main |
---|
5075 | import .fmt. |
---|
5076 | import "example/M" |
---|
5077 | |
---|
5078 | func main() int32 { |
---|
5079 | fmt.Printf(.%v., M.Inc(100)) |
---|
5080 | } |
---|
5081 | pub mod example { |
---|
5082 | pub mod M { |
---|
5083 | pub inc(val i32) -> i32 { |
---|
5084 | return val + 100; |
---|
5085 | } |
---|
5086 | } |
---|
5087 | } |
---|
5088 | |
---|
5089 | -------------------------------------- |
---|
5090 | //Use the module in another file |
---|
5091 | use example::M; |
---|
5092 | |
---|
5093 | |
---|
5094 | |
---|
5095 | fn main() { |
---|
5096 | println!(.{}., M::inc(100)); |
---|
5097 | } |
---|
5098 | \end{cfa} |
---|
5099 | |
---|
5100 | |
---|
5101 | \subsubsection{Parallel Tasks} |
---|
5102 | |
---|
5103 | \begin{flushleft} |
---|
5104 | \begin{tabular}{@{}l|l|l|l@{}} |
---|
5105 | \multicolumn{1}{c|}{\textbf{\CFA}} & \multicolumn{1}{c|}{\textbf{\CC}} & \multicolumn{1}{c|}{\textbf{Go}} & \multicolumn{1}{c}{\textbf{Rust}} \\ |
---|
5106 | \hline |
---|
5107 | \begin{cfa} |
---|
5108 | task Nonzero { |
---|
5109 | int *data; |
---|
5110 | int start; |
---|
5111 | int end; |
---|
5112 | int* res; |
---|
5113 | }; |
---|
5114 | |
---|
5115 | void ?{}(Nonzero &a, int d[], int s, |
---|
5116 | int e, int* subres) { |
---|
5117 | // constructor |
---|
5118 | a.data = d; |
---|
5119 | a.start = s; |
---|
5120 | a.end = e; |
---|
5121 | a.res = subres; |
---|
5122 | } |
---|
5123 | |
---|
5124 | // implicitly spawn thread here |
---|
5125 | void ?()(NonzeroCounter &a) { |
---|
5126 | int i; |
---|
5127 | int nonzero = 0; |
---|
5128 | for (i=start; c<end; ++i) { |
---|
5129 | if(a.data[i]!=0){ nonzero++;} |
---|
5130 | } |
---|
5131 | *a.res = nonzero; |
---|
5132 | } |
---|
5133 | |
---|
5134 | int main() { |
---|
5135 | int sz = ... |
---|
5136 | int data[sz] = ...; |
---|
5137 | int r1 = 0, r2=0; |
---|
5138 | int res; |
---|
5139 | { // create a scope for Nonzero |
---|
5140 | Nonzero n1{data, 0, sz/2, &n1}; |
---|
5141 | Nonzero n2{data, sz/2, sz, &n2}; |
---|
5142 | n1();//spawn |
---|
5143 | n2();//spawn |
---|
5144 | } |
---|
5145 | res = r1+r2; |
---|
5146 | return res; |
---|
5147 | } |
---|
5148 | \end{cfa} |
---|
5149 | & |
---|
5150 | \begin{cfa} |
---|
5151 | #include <thread> |
---|
5152 | #include <mutex> |
---|
5153 | |
---|
5154 | std::mutex m; |
---|
5155 | |
---|
5156 | |
---|
5157 | |
---|
5158 | |
---|
5159 | |
---|
5160 | |
---|
5161 | |
---|
5162 | |
---|
5163 | |
---|
5164 | |
---|
5165 | |
---|
5166 | |
---|
5167 | void task(const vector<int>&v, |
---|
5168 | int* res, size_t s, |
---|
5169 | size_t e) { |
---|
5170 | int non_zero = 0; |
---|
5171 | for(size_t i = s; i < e; ++i){ |
---|
5172 | if(v[i]!=0) { non_zero++;} |
---|
5173 | } |
---|
5174 | std::unique_lock<mutex> lck {m}; |
---|
5175 | *res += non_zero; |
---|
5176 | } |
---|
5177 | |
---|
5178 | int main() { |
---|
5179 | vector<int> data = ...; //data |
---|
5180 | int res = 0; |
---|
5181 | std::thread t1 {task, ref(data), |
---|
5182 | &res, 0, |
---|
5183 | data.size()/2}; |
---|
5184 | std::thread t2 {task, ref(data), |
---|
5185 | &res, data.size()/2, |
---|
5186 | data.size()}; |
---|
5187 | t1.join(); |
---|
5188 | t2.join(); |
---|
5189 | return res; |
---|
5190 | } |
---|
5191 | \end{cfa} |
---|
5192 | & |
---|
5193 | \begin{cfa} |
---|
5194 | package main |
---|
5195 | |
---|
5196 | import "fmt" |
---|
5197 | |
---|
5198 | func nonzero(data []int, c chan int) { |
---|
5199 | nz := 0 |
---|
5200 | for _, v:=range data { |
---|
5201 | if(v!=0) { nz := nz+1 } |
---|
5202 | } |
---|
5203 | c <- nz |
---|
5204 | } |
---|
5205 | |
---|
5206 | func main() { |
---|
5207 | sz := ... |
---|
5208 | data := make([]int, sz) |
---|
5209 | ... // data init |
---|
5210 | go nonzero(data[:len(data)/2], c) |
---|
5211 | go nonzero(data[len(data)/2:], c) |
---|
5212 | n1, n2 := <-c, <-c |
---|
5213 | res := n1 + n2 |
---|
5214 | fmt.Println(res) |
---|
5215 | } |
---|
5216 | \end{cfa} |
---|
5217 | & |
---|
5218 | \begin{cfa} |
---|
5219 | use std::thread; |
---|
5220 | use std::sync:mpsc::channel; |
---|
5221 | |
---|
5222 | fn main() { |
---|
5223 | let sz = ...; |
---|
5224 | let mut data:Vec<i32> = |
---|
5225 | Vec::with_capacity(sz as usize); |
---|
5226 | ... //init data |
---|
5227 | let (tx, rx) = channel(); |
---|
5228 | for i in 0..1 { |
---|
5229 | let tx = tx.clone(); |
---|
5230 | let data = data.clone() |
---|
5231 | thread::spawn(move|| { |
---|
5232 | let mut nz := 0; |
---|
5233 | let mut s = 0; |
---|
5234 | let mut e = sz / 2; |
---|
5235 | if i == 1 { |
---|
5236 | s = sz/2; |
---|
5237 | e = data.len(); |
---|
5238 | } |
---|
5239 | for i in s..(e - 1) { |
---|
5240 | if data[i] != 0 ( |
---|
5241 | nz = nz + 1 |
---|
5242 | } |
---|
5243 | } |
---|
5244 | tx.send(nz).unwrap(); |
---|
5245 | }); |
---|
5246 | } |
---|
5247 | let res = rx.recv().unwrap() + |
---|
5248 | rx.recv().unwrap(); |
---|
5249 | println!(.{}., res); |
---|
5250 | } |
---|
5251 | \end{cfa} |
---|
5252 | \end{tabular} |
---|
5253 | \end{flushleft} |
---|
5254 | |
---|
5255 | }% local change to lstlising to reduce font size |
---|
5256 | |
---|
5257 | |
---|
5258 | \subsection{Summary of Language Comparison} |
---|
5259 | \end{comment} |
---|
5260 | |
---|
5261 | |
---|
5262 | \subsection[C++]{\CC} |
---|
5263 | |
---|
5264 | \Index*[C++]{\CC{}} is a general-purpose programming language. |
---|
5265 | It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. (Wikipedia) |
---|
5266 | |
---|
5267 | The primary focus of \CC seems to be adding object-oriented programming to C, and this is the primary difference between \CC and Do. |
---|
5268 | \CC uses classes to encapsulate data and the functions that operate on that data, and to hide the internal representation of the data. |
---|
5269 | \CFA uses modules instead to perform these same tasks. |
---|
5270 | Classes in \CC also enable inheritance among types. |
---|
5271 | Instead of inheritance, \CFA embraces composition and interfaces to achieve the same goals with more flexibility. |
---|
5272 | There are many studies and articles comparing inheritance and composition (or is-a versus has-a relationships), so we will not go into more detail here (Venners, 1998) (Pike, \Index*{Go} at Google: Language Design in the Service of Software Engineering , 2012). |
---|
5273 | |
---|
5274 | 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. |
---|
5275 | References and exceptions in \CFA are heavily based on the same features from \CC. |
---|
5276 | The mechanism for interoperating with C code in \CFA is also borrowed from \CC. |
---|
5277 | |
---|
5278 | Both \CFA and \CC provide generics, and the syntax is quite similar. |
---|
5279 | 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. |
---|
5280 | This means that a generic function can be defined in a compiled library, and still be used as expected from source. |
---|
5281 | |
---|
5282 | |
---|
5283 | \subsection{Go} |
---|
5284 | |
---|
5285 | \Index*{Go}, also commonly referred to as golang, is a programming language developed at Google in 2007 [.]. |
---|
5286 | It is a statically typed language with syntax loosely derived from that of C, adding garbage collection, type |
---|
5287 | safety, some structural typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library. (Wikipedia) |
---|
5288 | |
---|
5289 | Go and \CFA differ significantly in syntax and implementation, but the underlying core concepts of the two languages are aligned. |
---|
5290 | Both Go and \CFA use composition and interfaces as opposed to inheritance to enable encapsulation and abstraction. |
---|
5291 | Both languages (along with their tooling ecosystem) provide a simple packaging mechanism for building units of code for easy sharing and reuse. |
---|
5292 | 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. |
---|
5293 | |
---|
5294 | Go has a significant runtime which handles the scheduling of its light weight threads, and performs garbage collection, among other tasks. |
---|
5295 | \CFA uses a cooperative scheduling algorithm for its tasks, and uses automatic reference counting to enable advanced memory management without garbage collection. |
---|
5296 | This results in Go requiring significant overhead to interface with C libraries while \CFA has no overhead. |
---|
5297 | |
---|
5298 | |
---|
5299 | \subsection{Rust} |
---|
5300 | |
---|
5301 | \Index*{Rust} is a general-purpose, multi-paradigm, compiled programming language developed by Mozilla Research. |
---|
5302 | 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. |
---|
5303 | |
---|
5304 | The primary focus of Rust is in safety, especially in concurrent programs. |
---|
5305 | To enforce a high level of safety, Rust has added ownership as a core feature of the language to guarantee memory safety. |
---|
5306 | 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. |
---|
5307 | |
---|
5308 | Aside from those key differences, Rust and \CFA also have several similarities. |
---|
5309 | Both languages support no overhead interoperability with C and have minimal runtimes. |
---|
5310 | Both languages support inheritance and polymorphism through the use of interfaces (traits). |
---|
5311 | |
---|
5312 | |
---|
5313 | \subsection{D} |
---|
5314 | |
---|
5315 | The \Index*{D} programming language is an object-oriented, imperative, multi-paradigm system programming |
---|
5316 | language created by Walter Bright of Digital Mars and released in 2001. [.] |
---|
5317 | Though it originated as a re-engineering of \CC, D is a distinct language, having redesigned some core \CC features while also taking inspiration from other languages, notably \Index*{Java}, \Index*{Python}, Ruby, C\#, and Eiffel. |
---|
5318 | |
---|
5319 | D and \CFA both start with C and add productivity features. |
---|
5320 | The obvious difference is that D uses classes and inheritance while \CFA uses composition and interfaces. |
---|
5321 | D is closer to \CFA than \CC since it is limited to single inheritance and also supports interfaces. |
---|
5322 | Like \CC, and unlike \CFA, D uses garbage collection and has compile-time expanded templates. |
---|
5323 | D does not have any built-in concurrency constructs in the |
---|
5324 | language, though it does have a standard library for concurrency which includes the low-level primitives for concurrency. |
---|
5325 | |
---|
5326 | |
---|
5327 | \appendix |
---|
5328 | |
---|
5329 | |
---|
5330 | \section{Syntax Ambiguities} |
---|
5331 | |
---|
5332 | C has a number of syntax ambiguities, which are resolved by taking the longest sequence of overlapping characters that constitute a token. |
---|
5333 | For example, the program fragment ©x+++++y© is parsed as \lstinline[showspaces=true]@x ++ ++ + y@ because operator tokens ©++© and ©+© overlap. |
---|
5334 | Unfortunately, the longest sequence violates a constraint on increment operators, even though the parse \lstinline[showspaces=true]@x ++ + ++ y@ might yield a correct expression. |
---|
5335 | Hence, C programmers are aware that spaces have to added to disambiguate certain syntactic cases. |
---|
5336 | |
---|
5337 | In \CFA, there are ambiguous cases with dereference and operator identifiers, \eg ©int *?*?()©, where the string ©*?*?© can be interpreted as: |
---|
5338 | \begin{cfa} |
---|
5339 | *?§\color{red}\textvisiblespace§*? §\C{// dereference operator, dereference operator}§ |
---|
5340 | *§\color{red}\textvisiblespace§?*? §\C{// dereference, multiplication operator}§ |
---|
5341 | \end{cfa} |
---|
5342 | By default, the first interpretation is selected, which does not yield a meaningful parse. |
---|
5343 | Therefore, \CFA does a lexical look-ahead for the second case, and backtracks to return the leading unary operator and reparses the trailing operator identifier. |
---|
5344 | Otherwise a space is needed between the unary operator and operator identifier to disambiguate this common case. |
---|
5345 | |
---|
5346 | A similar issue occurs with the dereference, ©*?(...)©, and routine-call, ©?()(...)© identifiers. |
---|
5347 | The ambiguity occurs when the deference operator has no parameters: |
---|
5348 | \begin{cfa} |
---|
5349 | *?()§\color{red}\textvisiblespace...§ ; |
---|
5350 | *?()§\color{red}\textvisiblespace...§(...) ; |
---|
5351 | \end{cfa} |
---|
5352 | requiring arbitrary whitespace look-ahead for the routine-call parameter-list to disambiguate. |
---|
5353 | However, the dereference operator \emph{must} have a parameter/argument to dereference ©*?(...)©. |
---|
5354 | Hence, always interpreting the string ©*?()© as \lstinline[showspaces=true]@* ?()@ does not preclude any meaningful program. |
---|
5355 | |
---|
5356 | The remaining cases are with the increment/decrement operators and conditional expression, \eg: |
---|
5357 | \begin{cfa} |
---|
5358 | i++?§\color{red}\textvisiblespace...§(...); |
---|
5359 | i?++§\color{red}\textvisiblespace...§(...); |
---|
5360 | \end{cfa} |
---|
5361 | requiring arbitrary whitespace look-ahead for the operator parameter-list, even though that interpretation is an incorrect expression (juxtaposed identifiers). |
---|
5362 | Therefore, it is necessary to disambiguate these cases with a space: |
---|
5363 | \begin{cfa} |
---|
5364 | i++§\color{red}\textvisiblespace§? i : 0; |
---|
5365 | i?§\color{red}\textvisiblespace§++i : 0; |
---|
5366 | \end{cfa} |
---|
5367 | |
---|
5368 | |
---|
5369 | \section{\texorpdfstring{\CFA Keywords}{Cforall Keywords}} |
---|
5370 | \label{s:CFAKeywords} |
---|
5371 | |
---|
5372 | \CFA introduces the following new keywords. |
---|
5373 | |
---|
5374 | \begin{quote2} |
---|
5375 | \begin{tabular}{lllll} |
---|
5376 | \begin{tabular}{@{}l@{}} |
---|
5377 | ©_At© \\ |
---|
5378 | ©catch© \\ |
---|
5379 | ©catchResume© \\ |
---|
5380 | ©choose© \\ |
---|
5381 | ©coroutine© \\ |
---|
5382 | \end{tabular} |
---|
5383 | & |
---|
5384 | \begin{tabular}{@{}l@{}} |
---|
5385 | ©disable© \\ |
---|
5386 | ©dtype© \\ |
---|
5387 | ©enable© \\ |
---|
5388 | ©fallthrough© \\ |
---|
5389 | ©fallthru© \\ |
---|
5390 | \end{tabular} |
---|
5391 | & |
---|
5392 | \begin{tabular}{@{}l@{}} |
---|
5393 | ©finally© \\ |
---|
5394 | ©forall© \\ |
---|
5395 | ©ftype© \\ |
---|
5396 | ©lvalue© \\ |
---|
5397 | ©monitor© \\ |
---|
5398 | \end{tabular} |
---|
5399 | & |
---|
5400 | \begin{tabular}{@{}l@{}} |
---|
5401 | ©mutex© \\ |
---|
5402 | ©one_t© \\ |
---|
5403 | ©otype© \\ |
---|
5404 | ©throw© \\ |
---|
5405 | ©throwResume© \\ |
---|
5406 | \end{tabular} |
---|
5407 | & |
---|
5408 | \begin{tabular}{@{}l@{}} |
---|
5409 | ©trait© \\ |
---|
5410 | ©try© \\ |
---|
5411 | ©ttype© \\ |
---|
5412 | ©with© \\ |
---|
5413 | ©zero_t© \\ |
---|
5414 | \end{tabular} |
---|
5415 | \end{tabular} |
---|
5416 | \end{quote2} |
---|
5417 | |
---|
5418 | |
---|
5419 | \section{Incompatible} |
---|
5420 | |
---|
5421 | The following incompatibles exist between \CFA and C, and are similar to Annex C for \CC~\cite{C++14}. |
---|
5422 | |
---|
5423 | |
---|
5424 | \begin{enumerate} |
---|
5425 | \item |
---|
5426 | \begin{description} |
---|
5427 | \item[Change:] add new keywords \\ |
---|
5428 | New keywords are added to \CFA (see~\VRef{s:CFAKeywords}). |
---|
5429 | \item[Rationale:] keywords added to implement new semantics of \CFA. |
---|
5430 | \item[Effect on original feature:] change to semantics of well-defined feature. \\ |
---|
5431 | Any \Celeven programs using these keywords as identifiers are invalid \CFA programs. |
---|
5432 | \item[Difficulty of converting:] keyword clashes are accommodated by syntactic transformations using the \CFA backquote escape-mechanism (see~\VRef{s:BackquoteIdentifiers}). |
---|
5433 | \item[How widely used:] clashes among new \CFA keywords and existing identifiers are rare. |
---|
5434 | \end{description} |
---|
5435 | |
---|
5436 | \item |
---|
5437 | \begin{description} |
---|
5438 | \item[Change:] drop K\&R C declarations \\ |
---|
5439 | K\&R declarations allow an implicit base-type of ©int©, if no type is specified, plus an alternate syntax for declaring parameters. |
---|
5440 | \eg: |
---|
5441 | \begin{cfa} |
---|
5442 | x; §\C{// int x}§ |
---|
5443 | *y; §\C{// int *y}§ |
---|
5444 | f( p1, p2 ); §\C{// int f( int p1, int p2 );}§ |
---|
5445 | g( p1, p2 ) int p1, p2; §\C{// int g( int p1, int p2 );}§ |
---|
5446 | \end{cfa} |
---|
5447 | \CFA continues to support K\&R routine definitions: |
---|
5448 | \begin{cfa} |
---|
5449 | f( a, b, c ) §\C{// default int return}§ |
---|
5450 | int a, b; char c §\C{// K\&R parameter declarations}§ |
---|
5451 | { |
---|
5452 | ... |
---|
5453 | } |
---|
5454 | \end{cfa} |
---|
5455 | \item[Rationale:] dropped from \Celeven standard.\footnote{ |
---|
5456 | 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}} |
---|
5457 | \item[Effect on original feature:] original feature is deprecated. \\ |
---|
5458 | Any old C programs using these K\&R declarations are invalid \CFA programs. |
---|
5459 | \item[Difficulty of converting:] trivial to convert to \CFA. |
---|
5460 | \item[How widely used:] existing usages are rare. |
---|
5461 | \end{description} |
---|
5462 | |
---|
5463 | \item |
---|
5464 | \begin{description} |
---|
5465 | \item[Change:] type of character literal ©int© to ©char© to allow more intuitive overloading: |
---|
5466 | \begin{cfa} |
---|
5467 | int rtn( int i ); |
---|
5468 | int rtn( char c ); |
---|
5469 | rtn( 'x' ); §\C{// programmer expects 2nd rtn to be called}§ |
---|
5470 | \end{cfa} |
---|
5471 | \item[Rationale:] it is more intuitive for the call to ©rtn© to match the second version of definition of ©rtn© rather than the first. |
---|
5472 | In particular, output of ©char© variable now print a character rather than the decimal ASCII value of the character. |
---|
5473 | \begin{cfa} |
---|
5474 | sout | 'x' | " " | (int)'x' | endl; |
---|
5475 | x 120 |
---|
5476 | \end{cfa} |
---|
5477 | Having to cast ©'x'© to ©char© is non-intuitive. |
---|
5478 | \item[Effect on original feature:] change to semantics of well-defined feature that depend on: |
---|
5479 | \begin{cfa} |
---|
5480 | sizeof( 'x' ) == sizeof( int ) |
---|
5481 | \end{cfa} |
---|
5482 | no long work the same in \CFA programs. |
---|
5483 | \item[Difficulty of converting:] simple |
---|
5484 | \item[How widely used:] programs that depend upon ©sizeof( 'x' )© are rare and can be changed to ©sizeof(char)©. |
---|
5485 | \end{description} |
---|
5486 | |
---|
5487 | \item |
---|
5488 | \begin{description} |
---|
5489 | \item[Change:] make string literals ©const©: |
---|
5490 | \begin{cfa} |
---|
5491 | char * p = "abc"; §\C{// valid in C, deprecated in \CFA}§ |
---|
5492 | char * q = expr ? "abc" : "de"; §\C{// valid in C, invalid in \CFA}§ |
---|
5493 | \end{cfa} |
---|
5494 | The type of a string literal is changed from ©[] char© to ©const [] char©. |
---|
5495 | Similarly, the type of a wide string literal is changed from ©[] wchar_t© to ©const [] wchar_t©. |
---|
5496 | \item[Rationale:] This change is a safety issue: |
---|
5497 | \begin{cfa} |
---|
5498 | char * p = "abc"; |
---|
5499 | p[0] = 'w'; §\C{// segment fault or change constant literal}§ |
---|
5500 | \end{cfa} |
---|
5501 | The same problem occurs when passing a string literal to a routine that changes its argument. |
---|
5502 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5503 | \item[Difficulty of converting:] simple syntactic transformation, because string literals can be converted to ©char *©. |
---|
5504 | \item[How widely used:] programs that have a legitimate reason to treat string literals as pointers to potentially modifiable memory are rare. |
---|
5505 | \end{description} |
---|
5506 | |
---|
5507 | \item |
---|
5508 | \begin{description} |
---|
5509 | \item[Change:] remove \newterm{tentative definitions}, which only occurs at file scope: |
---|
5510 | \begin{cfa} |
---|
5511 | int i; §\C{// forward definition}§ |
---|
5512 | int *j = ®&i®; §\C{// forward reference, valid in C, invalid in \CFA}§ |
---|
5513 | int i = 0; §\C{// definition}§ |
---|
5514 | \end{cfa} |
---|
5515 | is valid in C, and invalid in \CFA because duplicate overloaded object definitions at the same scope level are disallowed. |
---|
5516 | This change makes it impossible to define mutually referential file-local static objects, if initializers are restricted to the syntactic forms of C. For example, |
---|
5517 | \begin{cfa} |
---|
5518 | struct X { int i; struct X *next; }; |
---|
5519 | static struct X a; §\C{// forward definition}§ |
---|
5520 | static struct X b = { 0, ®&a® }; §\C{// forward reference, valid in C, invalid in \CFA}§ |
---|
5521 | static struct X a = { 1, &b }; §\C{// definition}§ |
---|
5522 | \end{cfa} |
---|
5523 | \item[Rationale:] avoids having different initialization rules for builtin types and user-defined types. |
---|
5524 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5525 | \item[Difficulty of converting:] the initializer for one of a set of mutually-referential file-local static objects must invoke a routine call to achieve the initialization. |
---|
5526 | \item[How widely used:] seldom |
---|
5527 | \end{description} |
---|
5528 | |
---|
5529 | \item |
---|
5530 | \begin{description} |
---|
5531 | \item[Change:] have ©struct© introduce a scope for nested types: |
---|
5532 | \begin{cfa} |
---|
5533 | enum ®Colour® { R, G, B, Y, C, M }; |
---|
5534 | struct Person { |
---|
5535 | enum ®Colour® { R, G, B }; §\C{// nested type}§ |
---|
5536 | struct Face { §\C{// nested type}§ |
---|
5537 | ®Colour® Eyes, Hair; §\C{// type defined outside (1 level)}§ |
---|
5538 | }; |
---|
5539 | ®.Colour® shirt; §\C{// type defined outside (top level)}§ |
---|
5540 | ®Colour® pants; §\C{// type defined same level}§ |
---|
5541 | Face looks[10]; §\C{// type defined same level}§ |
---|
5542 | }; |
---|
5543 | ®Colour® c = R; §\C{// type/enum defined same level}§ |
---|
5544 | Person®.Colour® pc = Person®.®R; §\C{// type/enum defined inside}§ |
---|
5545 | Person®.®Face pretty; §\C{// type defined inside}§ |
---|
5546 | \end{cfa} |
---|
5547 | In C, the name of the nested types belongs to the same scope as the name of the outermost enclosing structure, \ie the nested types are hoisted to the scope of the outer-most type, which is not useful and confusing. |
---|
5548 | \CFA is C \emph{incompatible} on this issue, and provides semantics similar to \Index*[C++]{\CC{}}. |
---|
5549 | Nested types are not hoisted and can be referenced using the field selection operator ``©.©'', unlike the \CC scope-resolution operator ``©::©''. |
---|
5550 | \item[Rationale:] ©struct© scope is crucial to \CFA as an information structuring and hiding mechanism. |
---|
5551 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5552 | \item[Difficulty of converting:] Semantic transformation. |
---|
5553 | \item[How widely used:] C programs rarely have nest types because they are equivalent to the hoisted version. |
---|
5554 | \end{description} |
---|
5555 | |
---|
5556 | \item |
---|
5557 | \begin{description} |
---|
5558 | \item[Change:] In C++, the name of a nested class is local to its enclosing class. |
---|
5559 | \item[Rationale:] C++ classes have member functions which require that classes establish scopes. |
---|
5560 | \item[Difficulty of converting:] Semantic transformation. To make the struct type name visible in the scope of the enclosing struct, the struct tag could be declared in the scope of the enclosing struct, before the enclosing struct is defined. Example: |
---|
5561 | \begin{cfa} |
---|
5562 | struct Y; §\C{// struct Y and struct X are at the same scope}§ |
---|
5563 | struct X { |
---|
5564 | struct Y { /* ... */ } y; |
---|
5565 | }; |
---|
5566 | \end{cfa} |
---|
5567 | All the definitions of C struct types enclosed in other struct definitions and accessed outside the scope of the enclosing struct could be exported to the scope of the enclosing struct. |
---|
5568 | Note: this is a consequence of the difference in scope rules, which is documented in 3.3. |
---|
5569 | \item[How widely used:] Seldom. |
---|
5570 | \end{description} |
---|
5571 | |
---|
5572 | \item |
---|
5573 | \begin{description} |
---|
5574 | \item[Change:] comma expression is disallowed as subscript |
---|
5575 | \item[Rationale:] safety issue to prevent subscripting error for multidimensional arrays: ©x[i,j]© instead of ©x[i][j]©, and this syntactic form then taken by \CFA for new style arrays. |
---|
5576 | \item[Effect on original feature:] change to semantics of well-defined feature. |
---|
5577 | \item[Difficulty of converting:] semantic transformation of ©x[i,j]© to ©x[(i,j)]© |
---|
5578 | \item[How widely used:] seldom. |
---|
5579 | \end{description} |
---|
5580 | \end{enumerate} |
---|
5581 | |
---|
5582 | |
---|
5583 | \section{Standard Headers} |
---|
5584 | \label{s:StandardHeaders} |
---|
5585 | |
---|
5586 | \Celeven prescribes the following standard header-files~\cite[\S~7.1.2]{C11} and \CFA adds to this list: |
---|
5587 | \begin{quote2} |
---|
5588 | \begin{tabular}{@{}lllll|l@{}} |
---|
5589 | \multicolumn{5}{c|}{C11} & \multicolumn{1}{c}{\CFA} \\ |
---|
5590 | \hline |
---|
5591 | \begin{tabular}{@{}l@{}} |
---|
5592 | \Indexc{assert.h} \\ |
---|
5593 | \Indexc{complex.h} \\ |
---|
5594 | \Indexc{ctype.h} \\ |
---|
5595 | \Indexc{errno.h} \\ |
---|
5596 | \Indexc{fenv.h} \\ |
---|
5597 | \Indexc[deletekeywords=float]{float.h} \\ |
---|
5598 | \end{tabular} |
---|
5599 | & |
---|
5600 | \begin{tabular}{@{}l@{}} |
---|
5601 | \Indexc{inttypes.h} \\ |
---|
5602 | \Indexc{iso646.h} \\ |
---|
5603 | \Indexc{limits.h} \\ |
---|
5604 | \Indexc{locale.h} \\ |
---|
5605 | \Indexc{math.h} \\ |
---|
5606 | \Indexc{setjmp.h} \\ |
---|
5607 | \end{tabular} |
---|
5608 | & |
---|
5609 | \begin{tabular}{@{}l@{}} |
---|
5610 | \Indexc{signal.h} \\ |
---|
5611 | \Indexc{stdalign.h} \\ |
---|
5612 | \Indexc{stdarg.h} \\ |
---|
5613 | \Indexc{stdatomic.h} \\ |
---|
5614 | \Indexc{stdbool.h} \\ |
---|
5615 | \Indexc{stddef.h} \\ |
---|
5616 | \end{tabular} |
---|
5617 | & |
---|
5618 | \begin{tabular}{@{}l@{}} |
---|
5619 | \Indexc{stdint.h} \\ |
---|
5620 | \Indexc{stdio.h} \\ |
---|
5621 | \Indexc{stdlib.h} \\ |
---|
5622 | \Indexc{stdnoreturn.h} \\ |
---|
5623 | \Indexc{string.h} \\ |
---|
5624 | \Indexc{tgmath.h} \\ |
---|
5625 | \end{tabular} |
---|
5626 | & |
---|
5627 | \begin{tabular}{@{}l@{}} |
---|
5628 | \Indexc{threads.h} \\ |
---|
5629 | \Indexc{time.h} \\ |
---|
5630 | \Indexc{uchar.h} \\ |
---|
5631 | \Indexc{wchar.h} \\ |
---|
5632 | \Indexc{wctype.h} \\ |
---|
5633 | \\ |
---|
5634 | \end{tabular} |
---|
5635 | & |
---|
5636 | \begin{tabular}{@{}l@{}} |
---|
5637 | \Indexc{unistd.h} \\ |
---|
5638 | \Indexc{gmp.h} \\ |
---|
5639 | \\ |
---|
5640 | \\ |
---|
5641 | \\ |
---|
5642 | \\ |
---|
5643 | \end{tabular} |
---|
5644 | \end{tabular} |
---|
5645 | \end{quote2} |
---|
5646 | For the prescribed head-files, \CFA uses header interposition to wraps these includes in an ©extern "C"©; |
---|
5647 | hence, names in these include files are not mangled\index{mangling!name} (see~\VRef{s:Interoperability}). |
---|
5648 | All other C header files must be explicitly wrapped in ©extern "C"© to prevent name mangling. |
---|
5649 | For \Index*[C++]{\CC{}}, the name-mangling issue is handled implicitly because most C header-files are augmented with checks for preprocessor variable ©__cplusplus©, which adds appropriate ©extern "C"© qualifiers. |
---|
5650 | |
---|
5651 | |
---|
5652 | \section{Standard Library} |
---|
5653 | \label{s:StandardLibrary} |
---|
5654 | |
---|
5655 | The \CFA standard-library wraps explicitly-polymorphic C routines into implicitly-polymorphic versions. |
---|
5656 | |
---|
5657 | |
---|
5658 | \subsection{Storage Management} |
---|
5659 | |
---|
5660 | The storage-management routines extend their C equivalents by overloading, alternate names, providing shallow type-safety, and removing the need to specify the allocation size for non-array types. |
---|
5661 | |
---|
5662 | Storage management provides the following capabilities: |
---|
5663 | \begin{description} |
---|
5664 | \item[fill] |
---|
5665 | after allocation the storage is filled with a specified character. |
---|
5666 | \item[resize] |
---|
5667 | an existing allocation is decreased or increased in size. |
---|
5668 | In either case, new storage may or may not be allocated and, if there is a new allocation, as much data from the existing allocation is copied. |
---|
5669 | For an increase in storage size, new storage after the copied data may be filled. |
---|
5670 | \item[alignment] |
---|
5671 | an allocation starts on a specified memory boundary, \eg, an address multiple of 64 or 128 for cache-line purposes. |
---|
5672 | \item[array] |
---|
5673 | the allocation size is scaled to the specified number of array elements. |
---|
5674 | An array may be filled, resized, or aligned. |
---|
5675 | \end{description} |
---|
5676 | The table shows allocation routines supporting different combinations of storage-management capabilities: |
---|
5677 | \begin{center} |
---|
5678 | \begin{tabular}{@{}r|r|l|l|l|l@{}} |
---|
5679 | \multicolumn{1}{c}{}& & \multicolumn{1}{c|}{fill} & resize & alignment & array \\ |
---|
5680 | \hline |
---|
5681 | C & ©malloc© & no & no & no & no \\ |
---|
5682 | & ©calloc© & yes (0 only) & no & no & yes \\ |
---|
5683 | & ©realloc© & no/copy & yes & no & no \\ |
---|
5684 | & ©memalign© & no & no & yes & no \\ |
---|
5685 | & ©posix_memalign© & no & no & yes & no \\ |
---|
5686 | \hline |
---|
5687 | C11 & ©aligned_alloc© & no & no & yes & no \\ |
---|
5688 | \hline |
---|
5689 | \CFA & ©alloc© & no/copy/yes & no/yes & no & yes \\ |
---|
5690 | & ©align_alloc© & no/yes & no & yes & yes \\ |
---|
5691 | \end{tabular} |
---|
5692 | \end{center} |
---|
5693 | It is impossible to resize with alignment because the underlying ©realloc© allocates storage if more space is needed, and it does not honour alignment from the original allocation. |
---|
5694 | |
---|
5695 | \leavevmode |
---|
5696 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5697 | // C unsafe allocation |
---|
5698 | extern "C" { |
---|
5699 | void * malloc( size_t size );§\indexc{memset}§ |
---|
5700 | void * calloc( size_t dim, size_t size );§\indexc{calloc}§ |
---|
5701 | void * realloc( void * ptr, size_t size );§\indexc{realloc}§ |
---|
5702 | void * memalign( size_t align, size_t size );§\indexc{memalign}§ |
---|
5703 | int posix_memalign( void ** ptr, size_t align, size_t size );§\indexc{posix_memalign}§ |
---|
5704 | } |
---|
5705 | |
---|
5706 | // §\CFA§ safe equivalents, i.e., implicit size specification |
---|
5707 | forall( dtype T | sized(T) ) T * malloc( void ); |
---|
5708 | forall( dtype T | sized(T) ) T * calloc( size_t dim ); |
---|
5709 | forall( dtype T | sized(T) ) T * realloc( T * ptr, size_t size ); |
---|
5710 | forall( dtype T | sized(T) ) T * memalign( size_t align ); |
---|
5711 | forall( dtype T | sized(T) ) T * aligned_alloc( size_t align ); |
---|
5712 | forall( dtype T | sized(T) ) int posix_memalign( T ** ptr, size_t align ); |
---|
5713 | |
---|
5714 | // §\CFA§ safe general allocation, fill, resize, array |
---|
5715 | forall( dtype T | sized(T) ) T * alloc( void );§\indexc{alloc}§ |
---|
5716 | forall( dtype T | sized(T) ) T * alloc( char fill ); |
---|
5717 | forall( dtype T | sized(T) ) T * alloc( size_t dim ); |
---|
5718 | forall( dtype T | sized(T) ) T * alloc( size_t dim, char fill ); |
---|
5719 | forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim ); |
---|
5720 | forall( dtype T | sized(T) ) T * alloc( T ptr[], size_t dim, char fill ); |
---|
5721 | |
---|
5722 | // §\CFA§ safe general allocation, align, fill, array |
---|
5723 | forall( dtype T | sized(T) ) T * align_alloc( size_t align ); |
---|
5724 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, char fill ); |
---|
5725 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim ); |
---|
5726 | forall( dtype T | sized(T) ) T * align_alloc( size_t align, size_t dim, char fill ); |
---|
5727 | |
---|
5728 | // C unsafe initialization/copy |
---|
5729 | extern "C" { |
---|
5730 | void * memset( void * dest, int c, size_t size ); |
---|
5731 | void * memcpy( void * dest, const void * src, size_t size ); |
---|
5732 | } |
---|
5733 | |
---|
5734 | // §\CFA§ safe initialization/copy, i.e., implicit size specification |
---|
5735 | forall( dtype T | sized(T) ) T * memset( T * dest, char c );§\indexc{memset}§ |
---|
5736 | forall( dtype T | sized(T) ) T * memcpy( T * dest, const T * src );§\indexc{memcpy}§ |
---|
5737 | |
---|
5738 | // §\CFA§ safe initialization/copy array |
---|
5739 | forall( dtype T | sized(T) ) T * memset( T dest[], size_t dim, char c ); |
---|
5740 | forall( dtype T | sized(T) ) T * memcpy( T dest[], const T src[], size_t dim ); |
---|
5741 | |
---|
5742 | // §\CFA§ allocation/deallocation and constructor/destructor |
---|
5743 | forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * new( Params p );§\indexc{new}§ |
---|
5744 | forall( dtype T | { void ^?{}( T * ); } ) void delete( T * ptr );§\indexc{delete}§ |
---|
5745 | forall( dtype T, ttype Params | { void ^?{}( T * ); void delete( Params ); } ) |
---|
5746 | void delete( T * ptr, Params rest ); |
---|
5747 | |
---|
5748 | // §\CFA§ allocation/deallocation and constructor/destructor, array |
---|
5749 | forall( dtype T | sized(T), ttype Params | { void ?{}( T *, Params ); } ) T * anew( size_t dim, Params p );§\indexc{anew}§ |
---|
5750 | forall( dtype T | sized(T) | { void ^?{}( T * ); } ) void adelete( size_t dim, T arr[] );§\indexc{adelete}§ |
---|
5751 | forall( dtype T | sized(T) | { void ^?{}( T * ); }, ttype Params | { void adelete( Params ); } ) |
---|
5752 | void adelete( size_t dim, T arr[], Params rest ); |
---|
5753 | \end{cfa} |
---|
5754 | |
---|
5755 | |
---|
5756 | \subsection{Conversion} |
---|
5757 | |
---|
5758 | \leavevmode |
---|
5759 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5760 | int ato( const char * ptr );§\indexc{ato}§ |
---|
5761 | unsigned int ato( const char * ptr ); |
---|
5762 | long int ato( const char * ptr ); |
---|
5763 | unsigned long int ato( const char * ptr ); |
---|
5764 | long long int ato( const char * ptr ); |
---|
5765 | unsigned long long int ato( const char * ptr ); |
---|
5766 | float ato( const char * ptr ); |
---|
5767 | double ato( const char * ptr ); |
---|
5768 | long double ato( const char * ptr ); |
---|
5769 | float _Complex ato( const char * ptr ); |
---|
5770 | double _Complex ato( const char * ptr ); |
---|
5771 | long double _Complex ato( const char * ptr ); |
---|
5772 | |
---|
5773 | int strto( const char * sptr, char ** eptr, int base ); |
---|
5774 | unsigned int strto( const char * sptr, char ** eptr, int base ); |
---|
5775 | long int strto( const char * sptr, char ** eptr, int base ); |
---|
5776 | unsigned long int strto( const char * sptr, char ** eptr, int base ); |
---|
5777 | long long int strto( const char * sptr, char ** eptr, int base ); |
---|
5778 | unsigned long long int strto( const char * sptr, char ** eptr, int base ); |
---|
5779 | float strto( const char * sptr, char ** eptr ); |
---|
5780 | double strto( const char * sptr, char ** eptr ); |
---|
5781 | long double strto( const char * sptr, char ** eptr ); |
---|
5782 | float _Complex strto( const char * sptr, char ** eptr ); |
---|
5783 | double _Complex strto( const char * sptr, char ** eptr ); |
---|
5784 | long double _Complex strto( const char * sptr, char ** eptr ); |
---|
5785 | \end{cfa} |
---|
5786 | |
---|
5787 | |
---|
5788 | \subsection{Search / Sort} |
---|
5789 | |
---|
5790 | \leavevmode |
---|
5791 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5792 | forall( otype T | { int ?<?( T, T ); } ) §\C{// location}§ |
---|
5793 | T * bsearch( T key, const T * arr, size_t dim );§\indexc{bsearch}§ |
---|
5794 | |
---|
5795 | forall( otype T | { int ?<?( T, T ); } ) §\C{// position}§ |
---|
5796 | unsigned int bsearch( T key, const T * arr, size_t dim ); |
---|
5797 | |
---|
5798 | forall( otype T | { int ?<?( T, T ); } ) |
---|
5799 | void qsort( const T * arr, size_t dim );§\indexc{qsort}§ |
---|
5800 | \end{cfa} |
---|
5801 | |
---|
5802 | |
---|
5803 | \subsection{Absolute Value} |
---|
5804 | |
---|
5805 | \leavevmode |
---|
5806 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5807 | unsigned char abs( signed char );§\indexc{abs}§ |
---|
5808 | int abs( int ); |
---|
5809 | unsigned long int abs( long int ); |
---|
5810 | unsigned long long int abs( long long int ); |
---|
5811 | float abs( float ); |
---|
5812 | double abs( double ); |
---|
5813 | long double abs( long double ); |
---|
5814 | float abs( float _Complex ); |
---|
5815 | double abs( double _Complex ); |
---|
5816 | long double abs( long double _Complex ); |
---|
5817 | forall( otype T | { void ?{}( T *, zero_t ); int ?<?( T, T ); T -?( T ); } ) |
---|
5818 | T abs( T ); |
---|
5819 | \end{cfa} |
---|
5820 | |
---|
5821 | |
---|
5822 | \subsection{Random Numbers} |
---|
5823 | |
---|
5824 | \leavevmode |
---|
5825 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5826 | void rand48seed( long int s );§\indexc{rand48seed}§ |
---|
5827 | char rand48();§\indexc{rand48}§ |
---|
5828 | int rand48(); |
---|
5829 | unsigned int rand48(); |
---|
5830 | long int rand48(); |
---|
5831 | unsigned long int rand48(); |
---|
5832 | float rand48(); |
---|
5833 | double rand48(); |
---|
5834 | float _Complex rand48(); |
---|
5835 | double _Complex rand48(); |
---|
5836 | long double _Complex rand48(); |
---|
5837 | \end{cfa} |
---|
5838 | |
---|
5839 | |
---|
5840 | \subsection{Algorithms} |
---|
5841 | |
---|
5842 | \leavevmode |
---|
5843 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5844 | forall( otype T | { int ?<?( T, T ); } ) T min( T t1, T t2 );§\indexc{min}§ |
---|
5845 | forall( otype T | { int ?>?( T, T ); } ) T max( T t1, T t2 );§\indexc{max}§ |
---|
5846 | forall( otype T | { T min( T, T ); T max( T, T ); } ) T clamp( T value, T min_val, T max_val );§\indexc{clamp}§ |
---|
5847 | forall( otype T ) void swap( T * t1, T * t2 );§\indexc{swap}§ |
---|
5848 | \end{cfa} |
---|
5849 | |
---|
5850 | |
---|
5851 | \section{Math Library} |
---|
5852 | \label{s:Math Library} |
---|
5853 | |
---|
5854 | The \CFA math-library wraps explicitly-polymorphic C math-routines into implicitly-polymorphic versions. |
---|
5855 | |
---|
5856 | |
---|
5857 | \subsection{General} |
---|
5858 | |
---|
5859 | \leavevmode |
---|
5860 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5861 | float ?%?( float, float );§\indexc{fmod}§ |
---|
5862 | float fmod( float, float ); |
---|
5863 | double ?%?( double, double ); |
---|
5864 | double fmod( double, double ); |
---|
5865 | long double ?%?( long double, long double ); |
---|
5866 | long double fmod( long double, long double ); |
---|
5867 | |
---|
5868 | float remainder( float, float );§\indexc{remainder}§ |
---|
5869 | double remainder( double, double ); |
---|
5870 | long double remainder( long double, long double ); |
---|
5871 | |
---|
5872 | [ int, float ] remquo( float, float );§\indexc{remquo}§ |
---|
5873 | float remquo( float, float, int * ); |
---|
5874 | [ int, double ] remquo( double, double ); |
---|
5875 | double remquo( double, double, int * ); |
---|
5876 | [ int, long double ] remquo( long double, long double ); |
---|
5877 | long double remquo( long double, long double, int * ); |
---|
5878 | |
---|
5879 | [ int, float ] div( float, float ); // alternative name for remquo |
---|
5880 | float div( float, float, int * );§\indexc{div}§ |
---|
5881 | [ int, double ] div( double, double ); |
---|
5882 | double div( double, double, int * ); |
---|
5883 | [ int, long double ] div( long double, long double ); |
---|
5884 | long double div( long double, long double, int * ); |
---|
5885 | |
---|
5886 | float fma( float, float, float );§\indexc{fma}§ |
---|
5887 | double fma( double, double, double ); |
---|
5888 | long double fma( long double, long double, long double ); |
---|
5889 | |
---|
5890 | float fdim( float, float );§\indexc{fdim}§ |
---|
5891 | double fdim( double, double ); |
---|
5892 | long double fdim( long double, long double ); |
---|
5893 | |
---|
5894 | float nan( const char * );§\indexc{nan}§ |
---|
5895 | double nan( const char * ); |
---|
5896 | long double nan( const char * ); |
---|
5897 | \end{cfa} |
---|
5898 | |
---|
5899 | |
---|
5900 | \subsection{Exponential} |
---|
5901 | |
---|
5902 | \leavevmode |
---|
5903 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5904 | float exp( float );§\indexc{exp}§ |
---|
5905 | double exp( double ); |
---|
5906 | long double exp( long double ); |
---|
5907 | float _Complex exp( float _Complex ); |
---|
5908 | double _Complex exp( double _Complex ); |
---|
5909 | long double _Complex exp( long double _Complex ); |
---|
5910 | |
---|
5911 | float exp2( float );§\indexc{exp2}§ |
---|
5912 | double exp2( double ); |
---|
5913 | long double exp2( long double ); |
---|
5914 | float _Complex exp2( float _Complex ); |
---|
5915 | double _Complex exp2( double _Complex ); |
---|
5916 | long double _Complex exp2( long double _Complex ); |
---|
5917 | |
---|
5918 | float expm1( float );§\indexc{expm1}§ |
---|
5919 | double expm1( double ); |
---|
5920 | long double expm1( long double ); |
---|
5921 | |
---|
5922 | float log( float );§\indexc{log}§ |
---|
5923 | double log( double ); |
---|
5924 | long double log( long double ); |
---|
5925 | float _Complex log( float _Complex ); |
---|
5926 | double _Complex log( double _Complex ); |
---|
5927 | long double _Complex log( long double _Complex ); |
---|
5928 | |
---|
5929 | float log2( float );§\indexc{log2}§ |
---|
5930 | double log2( double ); |
---|
5931 | long double log2( long double ); |
---|
5932 | float _Complex log2( float _Complex ); |
---|
5933 | double _Complex log2( double _Complex ); |
---|
5934 | long double _Complex log2( long double _Complex ); |
---|
5935 | |
---|
5936 | float log10( float );§\indexc{log10}§ |
---|
5937 | double log10( double ); |
---|
5938 | long double log10( long double ); |
---|
5939 | float _Complex log10( float _Complex ); |
---|
5940 | double _Complex log10( double _Complex ); |
---|
5941 | long double _Complex log10( long double _Complex ); |
---|
5942 | |
---|
5943 | float log1p( float );§\indexc{log1p}§ |
---|
5944 | double log1p( double ); |
---|
5945 | long double log1p( long double ); |
---|
5946 | |
---|
5947 | int ilogb( float );§\indexc{ilogb}§ |
---|
5948 | int ilogb( double ); |
---|
5949 | int ilogb( long double ); |
---|
5950 | |
---|
5951 | float logb( float );§\indexc{logb}§ |
---|
5952 | double logb( double ); |
---|
5953 | long double logb( long double ); |
---|
5954 | \end{cfa} |
---|
5955 | |
---|
5956 | |
---|
5957 | \subsection{Power} |
---|
5958 | |
---|
5959 | \leavevmode |
---|
5960 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5961 | float sqrt( float );§\indexc{sqrt}§ |
---|
5962 | double sqrt( double ); |
---|
5963 | long double sqrt( long double ); |
---|
5964 | float _Complex sqrt( float _Complex ); |
---|
5965 | double _Complex sqrt( double _Complex ); |
---|
5966 | long double _Complex sqrt( long double _Complex ); |
---|
5967 | |
---|
5968 | float cbrt( float );§\indexc{cbrt}§ |
---|
5969 | double cbrt( double ); |
---|
5970 | long double cbrt( long double ); |
---|
5971 | |
---|
5972 | float hypot( float, float );§\indexc{hypot}§ |
---|
5973 | double hypot( double, double ); |
---|
5974 | long double hypot( long double, long double ); |
---|
5975 | |
---|
5976 | float pow( float, float );§\indexc{pow}§ |
---|
5977 | double pow( double, double ); |
---|
5978 | long double pow( long double, long double ); |
---|
5979 | float _Complex pow( float _Complex, float _Complex ); |
---|
5980 | double _Complex pow( double _Complex, double _Complex ); |
---|
5981 | long double _Complex pow( long double _Complex, long double _Complex ); |
---|
5982 | \end{cfa} |
---|
5983 | |
---|
5984 | |
---|
5985 | \subsection{Trigonometric} |
---|
5986 | |
---|
5987 | \leavevmode |
---|
5988 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
5989 | float sin( float );§\indexc{sin}§ |
---|
5990 | double sin( double ); |
---|
5991 | long double sin( long double ); |
---|
5992 | float _Complex sin( float _Complex ); |
---|
5993 | double _Complex sin( double _Complex ); |
---|
5994 | long double _Complex sin( long double _Complex ); |
---|
5995 | |
---|
5996 | float cos( float );§\indexc{cos}§ |
---|
5997 | double cos( double ); |
---|
5998 | long double cos( long double ); |
---|
5999 | float _Complex cos( float _Complex ); |
---|
6000 | double _Complex cos( double _Complex ); |
---|
6001 | long double _Complex cos( long double _Complex ); |
---|
6002 | |
---|
6003 | float tan( float );§\indexc{tan}§ |
---|
6004 | double tan( double ); |
---|
6005 | long double tan( long double ); |
---|
6006 | float _Complex tan( float _Complex ); |
---|
6007 | double _Complex tan( double _Complex ); |
---|
6008 | long double _Complex tan( long double _Complex ); |
---|
6009 | |
---|
6010 | float asin( float );§\indexc{asin}§ |
---|
6011 | double asin( double ); |
---|
6012 | long double asin( long double ); |
---|
6013 | float _Complex asin( float _Complex ); |
---|
6014 | double _Complex asin( double _Complex ); |
---|
6015 | long double _Complex asin( long double _Complex ); |
---|
6016 | |
---|
6017 | float acos( float );§\indexc{acos}§ |
---|
6018 | double acos( double ); |
---|
6019 | long double acos( long double ); |
---|
6020 | float _Complex acos( float _Complex ); |
---|
6021 | double _Complex acos( double _Complex ); |
---|
6022 | long double _Complex acos( long double _Complex ); |
---|
6023 | |
---|
6024 | float atan( float );§\indexc{atan}§ |
---|
6025 | double atan( double ); |
---|
6026 | long double atan( long double ); |
---|
6027 | float _Complex atan( float _Complex ); |
---|
6028 | double _Complex atan( double _Complex ); |
---|
6029 | long double _Complex atan( long double _Complex ); |
---|
6030 | |
---|
6031 | float atan2( float, float );§\indexc{atan2}§ |
---|
6032 | double atan2( double, double ); |
---|
6033 | long double atan2( long double, long double ); |
---|
6034 | |
---|
6035 | float atan( float, float ); // alternative name for atan2 |
---|
6036 | double atan( double, double );§\indexc{atan}§ |
---|
6037 | long double atan( long double, long double ); |
---|
6038 | \end{cfa} |
---|
6039 | |
---|
6040 | |
---|
6041 | \subsection{Hyperbolic} |
---|
6042 | |
---|
6043 | \leavevmode |
---|
6044 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
6045 | float sinh( float );§\indexc{sinh}§ |
---|
6046 | double sinh( double ); |
---|
6047 | long double sinh( long double ); |
---|
6048 | float _Complex sinh( float _Complex ); |
---|
6049 | double _Complex sinh( double _Complex ); |
---|
6050 | long double _Complex sinh( long double _Complex ); |
---|
6051 | |
---|
6052 | float cosh( float );§\indexc{cosh}§ |
---|
6053 | double cosh( double ); |
---|
6054 | long double cosh( long double ); |
---|
6055 | float _Complex cosh( float _Complex ); |
---|
6056 | double _Complex cosh( double _Complex ); |
---|
6057 | long double _Complex cosh( long double _Complex ); |
---|
6058 | |
---|
6059 | float tanh( float );§\indexc{tanh}§ |
---|
6060 | double tanh( double ); |
---|
6061 | long double tanh( long double ); |
---|
6062 | float _Complex tanh( float _Complex ); |
---|
6063 | double _Complex tanh( double _Complex ); |
---|
6064 | long double _Complex tanh( long double _Complex ); |
---|
6065 | |
---|
6066 | float asinh( float );§\indexc{asinh}§ |
---|
6067 | double asinh( double ); |
---|
6068 | long double asinh( long double ); |
---|
6069 | float _Complex asinh( float _Complex ); |
---|
6070 | double _Complex asinh( double _Complex ); |
---|
6071 | long double _Complex asinh( long double _Complex ); |
---|
6072 | |
---|
6073 | float acosh( float );§\indexc{acosh}§ |
---|
6074 | double acosh( double ); |
---|
6075 | long double acosh( long double ); |
---|
6076 | float _Complex acosh( float _Complex ); |
---|
6077 | double _Complex acosh( double _Complex ); |
---|
6078 | long double _Complex acosh( long double _Complex ); |
---|
6079 | |
---|
6080 | float atanh( float );§\indexc{atanh}§ |
---|
6081 | double atanh( double ); |
---|
6082 | long double atanh( long double ); |
---|
6083 | float _Complex atanh( float _Complex ); |
---|
6084 | double _Complex atanh( double _Complex ); |
---|
6085 | long double _Complex atanh( long double _Complex ); |
---|
6086 | \end{cfa} |
---|
6087 | |
---|
6088 | |
---|
6089 | \subsection{Error / Gamma} |
---|
6090 | |
---|
6091 | \leavevmode |
---|
6092 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
6093 | float erf( float );§\indexc{erf}§ |
---|
6094 | double erf( double ); |
---|
6095 | long double erf( long double ); |
---|
6096 | float _Complex erf( float _Complex ); |
---|
6097 | double _Complex erf( double _Complex ); |
---|
6098 | long double _Complex erf( long double _Complex ); |
---|
6099 | |
---|
6100 | float erfc( float );§\indexc{erfc}§ |
---|
6101 | double erfc( double ); |
---|
6102 | long double erfc( long double ); |
---|
6103 | float _Complex erfc( float _Complex ); |
---|
6104 | double _Complex erfc( double _Complex ); |
---|
6105 | long double _Complex erfc( long double _Complex ); |
---|
6106 | |
---|
6107 | float lgamma( float );§\indexc{lgamma}§ |
---|
6108 | double lgamma( double ); |
---|
6109 | long double lgamma( long double ); |
---|
6110 | float lgamma( float, int * ); |
---|
6111 | double lgamma( double, int * ); |
---|
6112 | long double lgamma( long double, int * ); |
---|
6113 | |
---|
6114 | float tgamma( float );§\indexc{tgamma}§ |
---|
6115 | double tgamma( double ); |
---|
6116 | long double tgamma( long double ); |
---|
6117 | \end{cfa} |
---|
6118 | |
---|
6119 | |
---|
6120 | \subsection{Nearest Integer} |
---|
6121 | |
---|
6122 | \leavevmode |
---|
6123 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
6124 | float floor( float );§\indexc{floor}§ |
---|
6125 | double floor( double ); |
---|
6126 | long double floor( long double ); |
---|
6127 | |
---|
6128 | float ceil( float );§\indexc{ceil}§ |
---|
6129 | double ceil( double ); |
---|
6130 | long double ceil( long double ); |
---|
6131 | |
---|
6132 | float trunc( float );§\indexc{trunc}§ |
---|
6133 | double trunc( double ); |
---|
6134 | long double trunc( long double ); |
---|
6135 | |
---|
6136 | float rint( float );§\indexc{rint}§ |
---|
6137 | long double rint( long double ); |
---|
6138 | long int rint( float ); |
---|
6139 | long int rint( double ); |
---|
6140 | long int rint( long double ); |
---|
6141 | long long int rint( float ); |
---|
6142 | long long int rint( double ); |
---|
6143 | long long int rint( long double ); |
---|
6144 | |
---|
6145 | long int lrint( float );§\indexc{lrint}§ |
---|
6146 | long int lrint( double ); |
---|
6147 | long int lrint( long double ); |
---|
6148 | long long int llrint( float ); |
---|
6149 | long long int llrint( double ); |
---|
6150 | long long int llrint( long double ); |
---|
6151 | |
---|
6152 | float nearbyint( float );§\indexc{nearbyint}§ |
---|
6153 | double nearbyint( double ); |
---|
6154 | long double nearbyint( long double ); |
---|
6155 | |
---|
6156 | float round( float );§\indexc{round}§ |
---|
6157 | long double round( long double ); |
---|
6158 | long int round( float ); |
---|
6159 | long int round( double ); |
---|
6160 | long int round( long double ); |
---|
6161 | long long int round( float ); |
---|
6162 | long long int round( double ); |
---|
6163 | long long int round( long double ); |
---|
6164 | |
---|
6165 | long int lround( float );§\indexc{lround}§ |
---|
6166 | long int lround( double ); |
---|
6167 | long int lround( long double ); |
---|
6168 | long long int llround( float ); |
---|
6169 | long long int llround( double ); |
---|
6170 | long long int llround( long double ); |
---|
6171 | \end{cfa} |
---|
6172 | |
---|
6173 | |
---|
6174 | \subsection{Manipulation} |
---|
6175 | |
---|
6176 | \leavevmode |
---|
6177 | \begin{cfa}[aboveskip=0pt,belowskip=0pt] |
---|
6178 | float copysign( float, float );§\indexc{copysign}§ |
---|
6179 | double copysign( double, double ); |
---|
6180 | long double copysign( long double, long double ); |
---|
6181 | |
---|
6182 | float frexp( float, int * );§\indexc{frexp}§ |
---|
6183 | double frexp( double, int * ); |
---|
6184 | long double frexp( long double, int * ); |
---|
6185 | |
---|
6186 | float ldexp( float, int );§\indexc{ldexp}§ |
---|
6187 | double ldexp( double, int ); |
---|
6188 | long double ldexp( long double, int ); |
---|
6189 | |
---|
6190 | [ float, float ] modf( float );§\indexc{modf}§ |
---|
6191 | float modf( float, float * ); |
---|
6192 | [ double, double ] modf( double ); |
---|
6193 | double modf( double, double * ); |
---|
6194 | [ long double, long double ] modf( long double ); |
---|
6195 | long double modf( long double, long double * ); |
---|
6196 | |
---|
6197 | float nextafter( float, float );§\indexc{nextafter}§ |
---|
6198 | double nextafter( double, double ); |
---|
6199 | long double nextafter( long double, long double ); |
---|
6200 | |
---|
6201 | float nexttoward( float, long double );§\indexc{nexttoward}§ |
---|
6202 | double nexttoward( double, long double ); |
---|
6203 | long double nexttoward( long double, long double ); |
---|
6204 | |
---|
6205 | float scalbn( float, int );§\indexc{scalbn}§ |
---|
6206 | double scalbn( double, int ); |
---|
6207 | long double scalbn( long double, int ); |
---|
6208 | |
---|
6209 | float scalbln( float, long int );§\indexc{scalbln}§ |
---|
6210 | double scalbln( double, long int ); |
---|
6211 | long double scalbln( long double, long int ); |
---|
6212 | \end{cfa} |
---|
6213 | |
---|
6214 | |
---|
6215 | \section{Multi-precision Integers} |
---|
6216 | \label{s:MultiPrecisionIntegers} |
---|
6217 | |
---|
6218 | \CFA has an interface to the GMP \Index{multi-precision} signed-integers~\cite{GMP}, similar to the \CC interface provided by GMP. |
---|
6219 | The \CFA interface wraps GMP routines into operator routines to make programming with multi-precision integers identical to using fixed-sized integers. |
---|
6220 | The \CFA type name for multi-precision signed-integers is \Indexc{Int} and the header file is \Indexc{gmp}. |
---|
6221 | |
---|
6222 | \begin{cfa} |
---|
6223 | void ?{}( Int * this ); §\C{// constructor}§ |
---|
6224 | void ?{}( Int * this, Int init ); |
---|
6225 | void ?{}( Int * this, zero_t ); |
---|
6226 | void ?{}( Int * this, one_t ); |
---|
6227 | void ?{}( Int * this, signed long int init ); |
---|
6228 | void ?{}( Int * this, unsigned long int init ); |
---|
6229 | void ?{}( Int * this, const char * val ); |
---|
6230 | void ^?{}( Int * this ); |
---|
6231 | |
---|
6232 | Int ?=?( Int * lhs, Int rhs ); §\C{// assignment}§ |
---|
6233 | Int ?=?( Int * lhs, long int rhs ); |
---|
6234 | Int ?=?( Int * lhs, unsigned long int rhs ); |
---|
6235 | Int ?=?( Int * lhs, const char * rhs ); |
---|
6236 | |
---|
6237 | char ?=?( char * lhs, Int rhs ); |
---|
6238 | short int ?=?( short int * lhs, Int rhs ); |
---|
6239 | int ?=?( int * lhs, Int rhs ); |
---|
6240 | long int ?=?( long int * lhs, Int rhs ); |
---|
6241 | unsigned char ?=?( unsigned char * lhs, Int rhs ); |
---|
6242 | unsigned short int ?=?( unsigned short int * lhs, Int rhs ); |
---|
6243 | unsigned int ?=?( unsigned int * lhs, Int rhs ); |
---|
6244 | unsigned long int ?=?( unsigned long int * lhs, Int rhs ); |
---|
6245 | |
---|
6246 | long int narrow( Int val ); |
---|
6247 | unsigned long int narrow( Int val ); |
---|
6248 | |
---|
6249 | int ?==?( Int oper1, Int oper2 ); §\C{// comparison}§ |
---|
6250 | int ?==?( Int oper1, long int oper2 ); |
---|
6251 | int ?==?( long int oper2, Int oper1 ); |
---|
6252 | int ?==?( Int oper1, unsigned long int oper2 ); |
---|
6253 | int ?==?( unsigned long int oper2, Int oper1 ); |
---|
6254 | |
---|
6255 | int ?!=?( Int oper1, Int oper2 ); |
---|
6256 | int ?!=?( Int oper1, long int oper2 ); |
---|
6257 | int ?!=?( long int oper1, Int oper2 ); |
---|
6258 | int ?!=?( Int oper1, unsigned long int oper2 ); |
---|
6259 | int ?!=?( unsigned long int oper1, Int oper2 ); |
---|
6260 | |
---|
6261 | int ?<?( Int oper1, Int oper2 ); |
---|
6262 | int ?<?( Int oper1, long int oper2 ); |
---|
6263 | int ?<?( long int oper2, Int oper1 ); |
---|
6264 | int ?<?( Int oper1, unsigned long int oper2 ); |
---|
6265 | int ?<?( unsigned long int oper2, Int oper1 ); |
---|
6266 | |
---|
6267 | int ?<=?( Int oper1, Int oper2 ); |
---|
6268 | int ?<=?( Int oper1, long int oper2 ); |
---|
6269 | int ?<=?( long int oper2, Int oper1 ); |
---|
6270 | int ?<=?( Int oper1, unsigned long int oper2 ); |
---|
6271 | int ?<=?( unsigned long int oper2, Int oper1 ); |
---|
6272 | |
---|
6273 | int ?>?( Int oper1, Int oper2 ); |
---|
6274 | int ?>?( Int oper1, long int oper2 ); |
---|
6275 | int ?>?( long int oper1, Int oper2 ); |
---|
6276 | int ?>?( Int oper1, unsigned long int oper2 ); |
---|
6277 | int ?>?( unsigned long int oper1, Int oper2 ); |
---|
6278 | |
---|
6279 | int ?>=?( Int oper1, Int oper2 ); |
---|
6280 | int ?>=?( Int oper1, long int oper2 ); |
---|
6281 | int ?>=?( long int oper1, Int oper2 ); |
---|
6282 | int ?>=?( Int oper1, unsigned long int oper2 ); |
---|
6283 | int ?>=?( unsigned long int oper1, Int oper2 ); |
---|
6284 | |
---|
6285 | Int +?( Int oper ); §\C{// arithmetic}§ |
---|
6286 | Int -?( Int oper ); |
---|
6287 | Int ~?( Int oper ); |
---|
6288 | |
---|
6289 | Int ?&?( Int oper1, Int oper2 ); |
---|
6290 | Int ?&?( Int oper1, long int oper2 ); |
---|
6291 | Int ?&?( long int oper1, Int oper2 ); |
---|
6292 | Int ?&?( Int oper1, unsigned long int oper2 ); |
---|
6293 | Int ?&?( unsigned long int oper1, Int oper2 ); |
---|
6294 | Int ?&=?( Int * lhs, Int rhs ); |
---|
6295 | |
---|
6296 | Int ?|?( Int oper1, Int oper2 ); |
---|
6297 | Int ?|?( Int oper1, long int oper2 ); |
---|
6298 | Int ?|?( long int oper1, Int oper2 ); |
---|
6299 | Int ?|?( Int oper1, unsigned long int oper2 ); |
---|
6300 | Int ?|?( unsigned long int oper1, Int oper2 ); |
---|
6301 | Int ?|=?( Int * lhs, Int rhs ); |
---|
6302 | |
---|
6303 | Int ?^?( Int oper1, Int oper2 ); |
---|
6304 | Int ?^?( Int oper1, long int oper2 ); |
---|
6305 | Int ?^?( long int oper1, Int oper2 ); |
---|
6306 | Int ?^?( Int oper1, unsigned long int oper2 ); |
---|
6307 | Int ?^?( unsigned long int oper1, Int oper2 ); |
---|
6308 | Int ?^=?( Int * lhs, Int rhs ); |
---|
6309 | |
---|
6310 | Int ?+?( Int addend1, Int addend2 ); |
---|
6311 | Int ?+?( Int addend1, long int addend2 ); |
---|
6312 | Int ?+?( long int addend2, Int addend1 ); |
---|
6313 | Int ?+?( Int addend1, unsigned long int addend2 ); |
---|
6314 | Int ?+?( unsigned long int addend2, Int addend1 ); |
---|
6315 | Int ?+=?( Int * lhs, Int rhs ); |
---|
6316 | Int ?+=?( Int * lhs, long int rhs ); |
---|
6317 | Int ?+=?( Int * lhs, unsigned long int rhs ); |
---|
6318 | Int ++?( Int * lhs ); |
---|
6319 | Int ?++( Int * lhs ); |
---|
6320 | |
---|
6321 | Int ?-?( Int minuend, Int subtrahend ); |
---|
6322 | Int ?-?( Int minuend, long int subtrahend ); |
---|
6323 | Int ?-?( long int minuend, Int subtrahend ); |
---|
6324 | Int ?-?( Int minuend, unsigned long int subtrahend ); |
---|
6325 | Int ?-?( unsigned long int minuend, Int subtrahend ); |
---|
6326 | Int ?-=?( Int * lhs, Int rhs ); |
---|
6327 | Int ?-=?( Int * lhs, long int rhs ); |
---|
6328 | Int ?-=?( Int * lhs, unsigned long int rhs ); |
---|
6329 | Int --?( Int * lhs ); |
---|
6330 | Int ?--( Int * lhs ); |
---|
6331 | |
---|
6332 | Int ?*?( Int multiplicator, Int multiplicand ); |
---|
6333 | Int ?*?( Int multiplicator, long int multiplicand ); |
---|
6334 | Int ?*?( long int multiplicand, Int multiplicator ); |
---|
6335 | Int ?*?( Int multiplicator, unsigned long int multiplicand ); |
---|
6336 | Int ?*?( unsigned long int multiplicand, Int multiplicator ); |
---|
6337 | Int ?*=?( Int * lhs, Int rhs ); |
---|
6338 | Int ?*=?( Int * lhs, long int rhs ); |
---|
6339 | Int ?*=?( Int * lhs, unsigned long int rhs ); |
---|
6340 | |
---|
6341 | Int ?/?( Int dividend, Int divisor ); |
---|
6342 | Int ?/?( Int dividend, unsigned long int divisor ); |
---|
6343 | Int ?/?( unsigned long int dividend, Int divisor ); |
---|
6344 | Int ?/?( Int dividend, long int divisor ); |
---|
6345 | Int ?/?( long int dividend, Int divisor ); |
---|
6346 | Int ?/=?( Int * lhs, Int rhs ); |
---|
6347 | Int ?/=?( Int * lhs, long int rhs ); |
---|
6348 | Int ?/=?( Int * lhs, unsigned long int rhs ); |
---|
6349 | |
---|
6350 | [ Int, Int ] div( Int dividend, Int divisor ); |
---|
6351 | [ Int, Int ] div( Int dividend, unsigned long int divisor ); |
---|
6352 | |
---|
6353 | Int ?%?( Int dividend, Int divisor ); |
---|
6354 | Int ?%?( Int dividend, unsigned long int divisor ); |
---|
6355 | Int ?%?( unsigned long int dividend, Int divisor ); |
---|
6356 | Int ?%?( Int dividend, long int divisor ); |
---|
6357 | Int ?%?( long int dividend, Int divisor ); |
---|
6358 | Int ?%=?( Int * lhs, Int rhs ); |
---|
6359 | Int ?%=?( Int * lhs, long int rhs ); |
---|
6360 | Int ?%=?( Int * lhs, unsigned long int rhs ); |
---|
6361 | |
---|
6362 | Int ?<<?( Int shiften, mp_bitcnt_t shift ); |
---|
6363 | Int ?<<=?( Int * lhs, mp_bitcnt_t shift ); |
---|
6364 | Int ?>>?( Int shiften, mp_bitcnt_t shift ); |
---|
6365 | Int ?>>=?( Int * lhs, mp_bitcnt_t shift ); |
---|
6366 | |
---|
6367 | Int abs( Int oper ); §\C{// number functions}§ |
---|
6368 | Int fact( unsigned long int N ); |
---|
6369 | Int gcd( Int oper1, Int oper2 ); |
---|
6370 | Int pow( Int base, unsigned long int exponent ); |
---|
6371 | Int pow( unsigned long int base, unsigned long int exponent ); |
---|
6372 | void srandom( gmp_randstate_t state ); |
---|
6373 | Int random( gmp_randstate_t state, mp_bitcnt_t n ); |
---|
6374 | Int random( gmp_randstate_t state, Int n ); |
---|
6375 | Int random( gmp_randstate_t state, mp_size_t max_size ); |
---|
6376 | int sgn( Int oper ); |
---|
6377 | Int sqrt( Int oper ); |
---|
6378 | |
---|
6379 | forall( dtype istype | istream( istype ) ) istype * ?|?( istype * is, Int * mp ); §\C{// I/O}§ |
---|
6380 | forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype * os, Int mp ); |
---|
6381 | \end{cfa} |
---|
6382 | |
---|
6383 | The following factorial programs contrast using GMP with the \CFA and C interfaces, where the output from these programs appears in \VRef[Figure]{f:MultiPrecisionFactorials}. |
---|
6384 | (Compile with flag \Indexc{-lgmp} to link with the GMP library.) |
---|
6385 | \begin{quote2} |
---|
6386 | \begin{tabular}{@{}l@{\hspace{\parindentlnth}}|@{\hspace{\parindentlnth}}l@{}} |
---|
6387 | \multicolumn{1}{c|@{\hspace{\parindentlnth}}}{\textbf{\CFA}} & \multicolumn{1}{@{\hspace{\parindentlnth}}c}{\textbf{C}} \\ |
---|
6388 | \hline |
---|
6389 | \begin{cfa} |
---|
6390 | #include <gmp>§\indexc{gmp}§ |
---|
6391 | int main( void ) { |
---|
6392 | sout | "Factorial Numbers" | endl; |
---|
6393 | Int fact = 1; |
---|
6394 | |
---|
6395 | sout | 0 | fact | endl; |
---|
6396 | for ( unsigned int i = 1; i <= 40; i += 1 ) { |
---|
6397 | fact *= i; |
---|
6398 | sout | i | fact | endl; |
---|
6399 | } |
---|
6400 | } |
---|
6401 | \end{cfa} |
---|
6402 | & |
---|
6403 | \begin{cfa} |
---|
6404 | #include <gmp.h>§\indexc{gmp.h}§ |
---|
6405 | int main( void ) { |
---|
6406 | ®gmp_printf®( "Factorial Numbers\n" ); |
---|
6407 | ®mpz_t® fact; |
---|
6408 | ®mpz_init_set_ui®( fact, 1 ); |
---|
6409 | ®gmp_printf®( "%d %Zd\n", 0, fact ); |
---|
6410 | for ( unsigned int i = 1; i <= 40; i += 1 ) { |
---|
6411 | ®mpz_mul_ui®( fact, fact, i ); |
---|
6412 | ®gmp_printf®( "%d %Zd\n", i, fact ); |
---|
6413 | } |
---|
6414 | } |
---|
6415 | \end{cfa} |
---|
6416 | \end{tabular} |
---|
6417 | \end{quote2} |
---|
6418 | |
---|
6419 | \begin{figure} |
---|
6420 | \begin{cfa} |
---|
6421 | Factorial Numbers |
---|
6422 | 0 1 |
---|
6423 | 1 1 |
---|
6424 | 2 2 |
---|
6425 | 3 6 |
---|
6426 | 4 24 |
---|
6427 | 5 120 |
---|
6428 | 6 720 |
---|
6429 | 7 5040 |
---|
6430 | 8 40320 |
---|
6431 | 9 362880 |
---|
6432 | 10 3628800 |
---|
6433 | 11 39916800 |
---|
6434 | 12 479001600 |
---|
6435 | 13 6227020800 |
---|
6436 | 14 87178291200 |
---|
6437 | 15 1307674368000 |
---|
6438 | 16 20922789888000 |
---|
6439 | 17 355687428096000 |
---|
6440 | 18 6402373705728000 |
---|
6441 | 19 121645100408832000 |
---|
6442 | 20 2432902008176640000 |
---|
6443 | 21 51090942171709440000 |
---|
6444 | 22 1124000727777607680000 |
---|
6445 | 23 25852016738884976640000 |
---|
6446 | 24 620448401733239439360000 |
---|
6447 | 25 15511210043330985984000000 |
---|
6448 | 26 403291461126605635584000000 |
---|
6449 | 27 10888869450418352160768000000 |
---|
6450 | 28 304888344611713860501504000000 |
---|
6451 | 29 8841761993739701954543616000000 |
---|
6452 | 30 265252859812191058636308480000000 |
---|
6453 | 31 8222838654177922817725562880000000 |
---|
6454 | 32 263130836933693530167218012160000000 |
---|
6455 | 33 8683317618811886495518194401280000000 |
---|
6456 | 34 295232799039604140847618609643520000000 |
---|
6457 | 35 10333147966386144929666651337523200000000 |
---|
6458 | 36 371993326789901217467999448150835200000000 |
---|
6459 | 37 13763753091226345046315979581580902400000000 |
---|
6460 | 38 523022617466601111760007224100074291200000000 |
---|
6461 | 39 20397882081197443358640281739902897356800000000 |
---|
6462 | 40 815915283247897734345611269596115894272000000000 |
---|
6463 | \end{cfa} |
---|
6464 | \caption{Multi-precision Factorials} |
---|
6465 | \label{f:MultiPrecisionFactorials} |
---|
6466 | \end{figure} |
---|
6467 | |
---|
6468 | |
---|
6469 | \section{Rational Numbers} |
---|
6470 | \label{s:RationalNumbers} |
---|
6471 | |
---|
6472 | Rational numbers are numbers written as a ratio, \ie as a fraction, where the numerator (top number) and the denominator (bottom number) are whole numbers. |
---|
6473 | When creating and computing with rational numbers, results are constantly reduced to keep the numerator and denominator as small as possible. |
---|
6474 | |
---|
6475 | \begin{cfa}[belowskip=0pt] |
---|
6476 | // implementation |
---|
6477 | struct Rational {§\indexc{Rational}§ |
---|
6478 | long int numerator, denominator; // invariant: denominator > 0 |
---|
6479 | }; // Rational |
---|
6480 | |
---|
6481 | Rational rational(); §\C{// constructors}§ |
---|
6482 | Rational rational( long int n ); |
---|
6483 | Rational rational( long int n, long int d ); |
---|
6484 | void ?{}( Rational * r, zero_t ); |
---|
6485 | void ?{}( Rational * r, one_t ); |
---|
6486 | |
---|
6487 | long int numerator( Rational r ); §\C{// numerator/denominator getter/setter}§ |
---|
6488 | long int numerator( Rational r, long int n ); |
---|
6489 | long int denominator( Rational r ); |
---|
6490 | long int denominator( Rational r, long int d ); |
---|
6491 | |
---|
6492 | int ?==?( Rational l, Rational r ); §\C{// comparison}§ |
---|
6493 | int ?!=?( Rational l, Rational r ); |
---|
6494 | int ?<?( Rational l, Rational r ); |
---|
6495 | int ?<=?( Rational l, Rational r ); |
---|
6496 | int ?>?( Rational l, Rational r ); |
---|
6497 | int ?>=?( Rational l, Rational r ); |
---|
6498 | |
---|
6499 | Rational -?( Rational r ); §\C{// arithmetic}§ |
---|
6500 | Rational ?+?( Rational l, Rational r ); |
---|
6501 | Rational ?-?( Rational l, Rational r ); |
---|
6502 | Rational ?*?( Rational l, Rational r ); |
---|
6503 | Rational ?/?( Rational l, Rational r ); |
---|
6504 | |
---|
6505 | double widen( Rational r ); §\C{// conversion}§ |
---|
6506 | Rational narrow( double f, long int md ); |
---|
6507 | |
---|
6508 | forall( dtype istype | istream( istype ) ) istype * ?|?( istype *, Rational * ); // I/O |
---|
6509 | forall( dtype ostype | ostream( ostype ) ) ostype * ?|?( ostype *, Rational ); |
---|
6510 | \end{cfa} |
---|
6511 | |
---|
6512 | |
---|
6513 | \bibliographystyle{plain} |
---|
6514 | \bibliography{cfa} |
---|
6515 | |
---|
6516 | |
---|
6517 | \addcontentsline{toc}{section}{\indexname} % add index name to table of contents |
---|
6518 | \begin{theindex} |
---|
6519 | Italic page numbers give the location of the main entry for the referenced term. |
---|
6520 | Plain page numbers denote uses of the indexed term. |
---|
6521 | Entries for grammar non-terminals are italicized. |
---|
6522 | A typewriter font is used for grammar terminals and program identifiers. |
---|
6523 | \indexspace |
---|
6524 | \input{user.ind} |
---|
6525 | \end{theindex} |
---|
6526 | |
---|
6527 | |
---|
6528 | \end{document} |
---|
6529 | |
---|
6530 | % Local Variables: % |
---|
6531 | % tab-width: 4 % |
---|
6532 | % fill-column: 100 % |
---|
6533 | % compile-command: "make" % |
---|
6534 | % End: % |
---|