% ======================================================================
% ======================================================================
\chapter{Introduction to \CFA}\label{s:cfa}
% ======================================================================
% ======================================================================

\section{Overview}
The following serves as an introduction to \CFA. \CFA is a layer over C, is transpiled to C and is largely considered to be an extension of C. Beyond C, it adds productivity features, libraries, a type system, and many other language constructions. However, \CFA stays true to C as a language, with most code revolving around \code{struct}'s and routines, and respects the same rules as C. \CFA is not object oriented as it has no notion of \code{this} and no classes or methods, but supports some object oriented adjacent ideas including costructors, destructors, and limited inheritance. \CFA is rich with interesting features, but a subset that is pertinent to this work will be discussed.

\section{References}
References in \CFA are similar to references in \CC, however in \CFA references are rebindable, and support multi-level referencing. References in \CFA are a layer of syntactic sugar over pointers to reduce the number of ref/deref operations needed with pointer usage. Some examples of references in \CFA are shown in Listing~\ref{l:cfa_ref}. Another related item to note is that the \CFA equivalent of \CC's \code{nullptr} is \code{0p}.

\begin{cfacode}[tabsize=3,caption={Example of \CFA references},label={l:cfa_ref}]
int i = 2;
int & ref_i = i;            // declare ref to i
int * ptr_i = &i;           // ptr to i

// address of ref_i is the same as address of i
assert( &ref_i == ptr_i );

int && ref_ref_i = ref_i;   // can have a ref to a ref
ref_i = 3;                  // set i to 3
int new_i = 4;

// syntax to rebind ref_i (must cancel implicit deref)
&ref_i = &new_i; // (&*)ref_i = &new_i; (sets underlying ptr)
\end{cfacode}


\section{Overloading}
In \CFA routines can be overloaded on parameter type, number of parameters, and return type. Variables can also be overloaded on type, meaning that two variables can have the same name so long as they have different types. The variables will be disambiguated via type, sometimes requiring a cast. The code snippet in Listing~\ref{l:cfa_overload} contains examples of overloading.


\begin{cfacode}[tabsize=3,caption={Example of \CFA function overloading},label={l:cfa_overload}]
int foo() { printf("A\n");  return 0;}
int foo( int bar ) { printf("B\n"); return 1; }
int foo( double bar ) { printf("C\n"); return 2; }
double foo( double bar ) { printf("D\n"); return 3;}
void foo( double bar ) { printf("%.0f\n", bar); }

int main() {
    foo();                  // prints A
    foo( 0 );               // prints B
    int a = foo( 0.0 );     // prints C
    double a = foo( 0.0 );  // prints D
    foo( a );               // prints 3
}
\end{cfacode}


\section{With Statement}
The with statement is a tool for exposing members of aggregate types within a scope in \CFA. It allows users to use fields of aggregate types without using their fully qualified name. This feature is also implemented in Pascal. It can exist as a stand-alone statement or it can be used on routines to expose fields in the body of the routine. An example is shown in Listing~\ref{l:cfa_with}.


\begin{cfacode}[tabsize=3,caption={Usage of \CFA with statement},label={l:cfa_with}]
struct obj {
    int a, b, c;
};
struct pair {
    double x, y;
};

// Stand-alone with stmt:
pair p;
with( p ) {
    x = 6.28;
    y = 1.73;
}

// Can be used on routines:
void foo( obj o, pair p ) with( o, p ) {
    a = 1;
    b = 2;
    c = 3;
    x = 3.14;
    y = 2.71;
}

// routine foo is equivalent to routine bar:
void bar( obj o, pair p ) {
    o.a = 1;
    o.b = 2;
    o.c = 3;
    p.x = 3.14;
    p.y = 2.71;
}
\end{cfacode}


\section{Operators}
Operators can be overloaded in \CFA with operator routines. Operators in \CFA are named using the operator symbol and '?' to respresent operands.
An example is shown in Listing~\ref{l:cfa_operate}.


\begin{cfacode}[tabsize=3,caption={Example of \CFA operators},label={l:cfa_operate}]
struct coord {
    double x;
    double y;
    double z;
};
coord ++?( coord & c ) with(c) {
    x++;
    y++;
    z++;
    return c;
}
coord ?<=?( coord op1, coord op2 ) with( op1 ) {
    return (x*x + y*y + z*z) <= 
        (op2.x*op2.x + op2.y*op2.y + op2.z*op2.z);
}
\end{cfacode}


\section{Constructors and Destructors}
Constructors and destructors in \CFA are two special operator routines that are used for creation and destruction of objects. The default constructor and destructor for a type are called implicitly upon creation and deletion respectively if they are defined. An example is shown in Listing~\ref{l:cfa_ctor}.


\begin{cfacode}[tabsize=3,caption={Example of \CFA constructors and destructors},label={l:cfa_ctor}]
struct discrete_point {
    int x;
    int y;
};
void ?{}( discrete_point & this ) with(this) { // ctor
    x = 0;
    y = 0;
}
void ?{}( discrete_point & this, int x, int y ) { // ctor
    this.x = x;
    this.y = y;
}
void ^?{}( discrete_point & this ) with(this) { // dtor
    x = 0;
    y = 0;
}

int main() {
    discrete_point d; // implicit call to ?{}
    discrete_point p{}; // same call as line above
    discrete_point dp{ 2, -4 }; // specialized ctor
} // ^d{}, ^p{}, ^dp{} all called as they go out of scope
\end{cfacode}


\section{Polymorphism}\label{s:poly}
C does not natively support polymorphism, and requires users to implement polymorphism themselves if they want to use it. \CFA extends C with two styles of polymorphism that it supports, parametric polymorphism and nominal inheritance.

\subsection{Parametric Polymorphism}
\CFA provides parametric polymorphism in the form of \code{forall}, and \code{trait}s. A \code{forall} takes in a set of types and a list of constraints. The declarations that follow the \code{forall} are parameterized over the types listed that satisfy the constraints. Sometimes the list of constraints can be long, which is where a \code{trait} can be used. A \code{trait} is a collection of constraints that is given a name and can be reused in foralls. An example of the usage of parametric polymorphism in \CFA is shown in Listing~\ref{l:cfa_poly}.

\begin{cfacode}[tabsize=3,caption={Example of \CFA polymorphism},label={l:cfa_poly}]
// sized() is a trait that means the type has a size
forall( V & | sized(V) )        // type params for trait
trait vector_space {
    V add( V, V );              // vector addition
    V scalar_mult( int, V );    // scalar multiplication

    // dtor and copy ctor needed in constraints to pass by copy
    void ?{}( V &, V & );       // copy ctor for return
    void ^?{}( V & );           // dtor
};

forall( V & | vector_space( V )) {
    V get_inverse( V v1 ) {
        return scalar_mult( -1, v1 );  // can use ?*? routine defined in trait
    }
    V add_and_invert( V v1, V v2 ) {
        return get_inverse( add( v1, v2 ) );  // can use ?*? routine defined in trait
    }
}
struct Vec1 { int x; };
void ?{}( Vec1 & this, Vec1 & other ) { this.x = other.x; }
void ?{}( Vec1 & this, int x ) { this.x = x; }
void ^?{}( Vec1 & this ) {}
Vec1 add( Vec1 v1, Vec1 v2 ) { v1.x += v2.x; return v1; }
Vec1 scalar_mult( int c, Vec1 v1 ) { v1.x = v1.x * c; return v1; }

struct Vec2 { int x; int y; };
void ?{}( Vec2 & this, Vec2 & other ) { this.x = other.x; this.y = other.y; }
void ?{}( Vec2 & this, int x ) { this.x = x; this.y = x; }
void ^?{}( Vec2 & this ) {}
Vec2 add( Vec2 v1, Vec2 v2 ) { v1.x += v2.x; v1.y += v2.y; return v1; }
Vec2 scalar_mult( int c, Vec2 v1 ) { v1.x = v1.x * c; v1.y = v1.y * c; return v1; }

int main() {
    Vec1 v1{ 1 }; // create Vec1 and call ctor
    Vec2 v2{ 2 }; // create Vec2 and call ctor

    // can use forall defined routines since types satisfy trait
    add_and_invert( get_inverse( v1 ), v1 );
    add_and_invert( get_inverse( v2 ), v2 );
}

\end{cfacode}

\subsection{Inheritance}
Inheritance in \CFA copies its style from Plan-9 C nominal inheritance. In \CFA structs can \code{inline} another struct type to gain its fields and to be able to be passed to routines that require a parameter of the inlined type. An example of \CFA inheritance is shown in Listing~\ref{l:cfa_inherit}.

\begin{cfacode}[tabsize=3,caption={Example of \CFA inheritance},label={l:cfa_inherit}]
struct one_d { double x; };
struct two_d { 
    inline one_d;
    double y;
};
struct three_d { 
    inline two_d;
    double z;
};
double get_x( one_d & d ){ return d.x; }

struct dog {};
struct dog_food {
    int count;
};
struct pet {
    inline dog;
    inline dog_food;
};
void pet_dog( dog & d ){printf("woof\n");}
void print_food( dog_food & f ){printf("%d\n", f.count);}

int main() {
    one_d x;
    two_d y;
    three_d z;
    x.x = 1;
    y.x = 2;
    z.x = 3;
    get_x( x ); // returns 1;
    get_x( y ); // returns 2;
    get_x( z ); // returns 3;
    pet p;
    p.count = 5;
    pet_dog( p );    // prints woof
    print_food( p ); // prints 5
}
\end{cfacode}


