Index: doc/theses/fangren_yu_MMath/future.tex
===================================================================
--- doc/theses/fangren_yu_MMath/future.tex	(revision 7d405eb2bce8247558b6173cc06a2d68843eb9e2)
+++ doc/theses/fangren_yu_MMath/future.tex	(revision 9fbc40e8adba86ceb318d8df9a796655673cfd4a)
@@ -1,143 +1,187 @@
 \chapter{Future Work}
 
-These are some feature requests related to type system enhancement that come up during the development of \CFA language and library, but have not been implemented yet. A lot of the current implementations have to work around the limits of the language features and sometimes lead to inefficiency. 
+\vspace*{-18pt}
+The following are feature requests related to type-system enhancements that have surfaced during the development of the \CFA language and library, but have not been implemented yet.
+Currently, developers must work around these missing features, sometimes resulting in inefficiency.
+
 
 \section{Closed trait types}
 
-\CFA as it currently is does not have any closed types, as new functions can be added at any time. It is also possible to locally declare a function,\footnote{Local functions are not a standard feature in C but supported by mainstream C compilers such as gcc, and allowed in \CFA too.} or a function pointer variable to make a type satisfy a certain trait temporarily and be used as such in this limited scope. However, the lack of closed types in such a "duck typing" scheme proposes two problems. For library implementors, it is common to not want the defined set of operations to be overwritten and cause the behaviour of polymorphic invocations to change. For the compiler, it means caching and reusing the result of resolution is not reliable as newly introduced declarations can participate in assertion resolution, making a previously invalid expression valid, or the other way around by introducing ambiguity in assertions. Sometimes those interfaces are fairly complicated, for example the I/O library traits \textbf{istream} and \textbf{ostream} each has over 20 operations. Without the ability to store and reuse assertion resolution results, each time the compiler encounters an I/O operation in the source code (mainly the pipe operator \textbf{?|?} used to represent stream operations in \CFA) it has to resolve the same set of assertions again, causing a lot of repetitive work. Previous experiments have shown that the I/O assertions often account for over half of the number of assertions resolved in a \CFA translation unit. Introducing a way to eliminate the need of doing such repetitive assertion resolutions that are very unlikely to change by new overloads can therefore provide significant improvement to the performance of the compiler.
+Currently, \CFA does not have any closed types, as open type are the basis of its unique type-system, allowing new functions to be added at any time to override existing ones for trait satisfaction.
+Locally-declared nested-functions,\footnote{
+Nested functions are not a feature in C but supported by \lstinline{gcc} for multiple decades and are used heavily in \CFA.}
+or a function-pointer variable can be used to make a type satisfy a certain trait temporarily in a limited lexical scope.
+However, the lack of closed types in such a \emph{duck typing} scheme presents two problems.
+\begin{enumerate}[leftmargin=*]
+\item
+Library implementers normally do not want users to override certain operations and cause the behaviour of polymorphic invocations to change.
+\item
+Caching and reusing resolution results in the compiler is effected, as newly introduced declarations can participate in assertion resolution;
+as a result, previously invalid subexpressions suddenly become valid, or alternatively cause ambiguity in assertions.
+\end{enumerate}
+Sometimes those interfaces are fairly complicated, \eg the \CFA I/O library traits @istream@ and @ostream@ each have over 20 operations.
+Without the ability to store and reuse assertion resolution results, each time the compiler encounters an I/O operation (denoted by the pipe operator @?|?@ like the @<<@, @>>@ stream operators in \CC) it has to resolve the same set of assertions again, causing a lot of repetitive work.
+Previous experiments have shown that the I/O assertions often account for over half of the number of assertions resolved in a \CFA translation unit.
+Hence, eliminating repetitive assertion resolution, which are very unlikely to change by new overloads, can provide a significant performance benefit.
 
-The output stream trait in \CFA looks like this:
+\VRef[Figure]{f:basicOstreamTrait} shows the basic output-stream trait in \CFA and the overloaded I/O operator is declared as:
+\begin{cfa}
+forall( ostype & | basic_ostream( ostype ) ) ostype & ?|?( ostype &, int ); // one for each basic type
+\end{cfa}
+The \CFA polymorphic calling convention means all of these trait functions are repeatedly resolved at each output-operator call-site and then become implicit arguments of the call.
+This creates both compile-time and run-time overheads.
+As stated, resolving assertions takes the most amount of time during compilation, and it is common to see in the current codebase and test suite that the majority of compilation time is spent in I/O statements.
+With closed types, the I/O assertions can be resolved once and this information reused everywhere.
+Furthermore, closed types can have a different calling convention of pushing a virtual-table pointer rather than individual arguments onto the stack.
+Although for I/O, this benefit might not be significant, since these operations involve system calls that are inherently slow.
 
+\begin{figure}
+\begin{cfa}[escapechar={\#}]
+forall( ostype & ) @trait@ basic_ostream {
+	// private
+	bool sepPrt$( ostype & );					#\C[3.35in]{// get separator state (on/off)}#
+	void sepReset$( ostype & );					#\C{// set separator state to default state}#
+	void sepReset$( ostype &, bool );			#\C{// set separator and default state}#
+	const char * sepGetCur$( ostype & );		#\C{// get current separator string}#
+	void sepSetCur$( ostype &, const char [] );	#\C{// set current separator string}#
+	bool getNL$( ostype & );					#\C{// get newline}#
+	bool setNL$( ostype &, bool );				#\C{// set newline}#
+	bool getANL$( ostype & );					#\C{// get auto newline (on/off)}#
+	bool setANL$( ostype &, bool );				#\C{// set auto newline (on/off)}#
+	bool getPrt$( ostype & );					#\C{// get fmt called in output cascade}#
+	bool setPrt$( ostype &, bool );				#\C{// set fmt called in output cascade}#
+	// public
+	void nlOn( ostype & );						#\C{// turn auto-newline state on}#
+	void nlOff( ostype & );						#\C{// turn auto-newline state off}#
+	void sep( ostype & );						#\C{// turn separator state on}#
+	void nosep( ostype & );						#\C{// turn separator state off}#
+	bool sepOn( ostype & );						#\C{// set default state to on}#
+	bool sepOff( ostype & );					#\C{// set default state to off}#
+	const char * sepGet( ostype & );			#\C{// get separator string}#
+	void sepSet( ostype &, const char [] );		#\C{// set separator to string (15 maximum)}#
+	const char * sepGetTuple( ostype & );		#\C{// get tuple separator string}#
+	void sepSetTuple( ostype &, const char [] );#\C{// set tuple separator to string (15 maximum)}#
+	void ends( ostype & );						#\C{// end of output statement}\CRT#
+	int fmt( ostype &, const char format[], ... ) __attribute__(( format(printf, 2, 3) ));
+};
+\end{cfa}
+\caption{\lstinline{basic_ostream} trait}
+\label{f:basicOstreamTrait}
+\end{figure}
+
+A \CFA closed trait type is similar to a Haskell type class requiring an explicit instance declaration.
+The syntax for the closed trait might look like:
 \begin{cfa}
-forall( ostype & )
-trait basic_ostream {
-	// private
-	bool sepPrt$\$$( ostype & );							// get separator state (on/off)
-    
-	void sepReset$\$$( ostype & );							// set separator state to default state
-	void sepReset$\$$( ostype &, bool );					// set separator and default state
-	const char * sepGetCur$\$$( ostype & );				// get current separator string
-	void sepSetCur$\$$( ostype &, const char [] );			// set current separator string
-	bool getNL$\$$( ostype & );							// get newline
-	bool setNL$\$$( ostype &, bool );						// set newline
-	bool getANL$\$$( ostype & );							// get auto newline (on/off)
-	bool setANL$\$$( ostype &, bool );						// set auto newline (on/off), and return previous state
-	bool getPrt$\$$( ostype & );							// get fmt called in output cascade
-	bool setPrt$\$$( ostype &, bool );						// set fmt called in output cascade
-	// public
-	void nlOn( ostype & );								// turn auto-newline state on
-	void nlOff( ostype & );								// turn auto-newline state off
-
-	void sep( ostype & );								// turn separator state on
-	void nosep( ostype & );								// turn separator state off
-	bool sepOn( ostype & );								// set default state to on, and return previous state
-	bool sepOff( ostype & );							// set default state to off, and return previous state
-	const char * sepGet( ostype & );					// get separator string
-	void sepSet( ostype &, const char [] );				// set separator to string (15 character maximum)
-	const char * sepGetTuple( ostype & );				// get tuple separator string
-	void sepSetTuple( ostype &, const char [] );		// set tuple separator to string (15 character maximum)
-
-	void ends( ostype & );								// end of output statement
-	int fmt( ostype &, const char format[], ... ) __attribute__(( format(printf, 2, 3) ));
-}; // basic_ostream
-
+forall( ostype & ) @closed@ trait basic_ostream { /* above declarations */ };
+@trait@ basic_ostream struct ofstream { ... }; // bind trait to type, implement basic_ostream
+\end{cfa}
+At the trait declaration, all the required trait functions must be inferred and specialized in the usual way.
+The list of inferred and specialized functions is then saved as an array of function pointers (vtable), and polymorphic functions using the closed type are passed the vtable, instead of a list of implicit parameters.
+\begin{cfa}
+ostype ?|?( ostype &, int, @basic_ostream_vtable *@ ); // parametric vtable
+sout | 42;   /* becomes */   ?|?( sout, 42, @ofstream_trait@ );  // generated for closed type ofstream
 \end{cfa}
 
-and the overloaded output operator is declared as
-
-\begin{cfa}
-forall( ostype & | basic_ostream( ostype ) ) ostype & ?|?( ostype &, int ); // also defined for all other basic types
-\end{cfa}
-
-The \CFA polymorphic calling convention makes the output operator take all the trait functions above as implicit arguments, and they are repeatedly resolved every time an output operator is called. This creates both compile-time and run-time overheads. \CFA compilation takes the most amount of time in resolving assertions, and it is not uncommon to see in the current codebase and test suite that the majority of time spent in compiling a program is due to a series of I/O statements, while resolving those assertions for I/O operators could have been a once and done job. Repeatedly pushing tens of arguments onto the stack to call these operators at run-time can also have some impact on performance, although in the I/O case it is not as significant, since these operations involve system calls which are already slow.
-
-An addition of closed trait type will make a \CFA trait behave similarly to a Haskell type class and require an explicit instance declaration as well. The syntax for closed trait is not settled yet, but it may look something like the following:
-
-\begin{cfa}
-    forall(ostype &)
-    closed trait basic_ostream{
-        // all the above declarations
-    };
-
-    struct ofstream {
-        // ... 
-    };
-
-    // implementation of trait functions for ofstream
-
-    __cfa_trait_instance(ofstream, basic_ostream);
-\end{cfa}
-
-At the point of instance declaration, all the required trait functions must be declared in scope, and they are inferred and specialized in the usual way. The list of inferred and specialized functions will then be saved into an array of function pointers, and polymorphic functions using the closed trait type can simply take the instance pointer, instead of a list of implicit parameters.
-
-\begin{cfa}
-    // original declaration
-    forall( ostype & | basic_ostream( ostype ) ) ostype & ?|?( ostype & os, int i); 
-
-    // translated code with closed trait
-    void* ?|?(void* os, int i, void* _instance_basic_ostream); 
-    // polymorphic pointer and reference types are erased
-
-    // call site
-    sout | 42;
-    
-    // generated code
-    ?|?(sout, 42, __cfa_instance_ofstream__basic_ostream /* generated by __cfa_trait_instance decl */);
-\end{cfa}
-
-Introducing closed trait types also comes with the additional benefit of the ability to achieve better encapsulation. In the above @basic_ostream@ example, the functions ending with dollar sign \$ are meant to be private (internal to the library) and the client code should not be able to see or call those functions directly. This is impossible with the current trait and assertion system, because the satisfying declarations must be visible at call site for the polymorphic call to resolve. With closed traits and instance types, it will be possible to forward declare a closed trait (which would not even make sense otherwise) and the instance pointer of a type implementing the trait without exposing any details to the client, since all the information necessary to call the trait functions are now captured in a single pointer to a table of functions built at compile time, and the type of that pointer is made opaque to the client.
-
-
+Closed types can provide additional encapsulation.
+In \VRef[Figure]{f:basicOstreamTrait}, the functions ending with dollar sign @$@ are meant to be private (internal to the library) so client code should not be able to see or call these functions directly.
+This kind of information hiding is impossible with the current trait and assertion system, because the trait information must be visible at the call site for the polymorphic call to resolve.
+With closed traits and types, it is possible to forward declare a closed trait (which does not make sense otherwise) and its vtable without exposing any details to the client.
+That is, all the information necessary to call trait functions is now captured in a single vtable pointer built at compile time and the type of the vtable pointer is opaque.
 
 
 \section{Associated Types}
 
-The analysis presented in section 4.3 shows that if we mandate that all type parameters have to be bound before assertion resolution, the complexity of resolving assertions become much lower as every assertion parameter can be resolved independently. By fully utilizing information from higher up the expression tree for return value overloading, most of the type bindings can be resolved. However there are certain scenarios where we would like to have some intermediate types to be involved in certain operations, that are neither input nor output types.
+The analysis presented in \VRef{s:AssertionSatisfaction} shows if all type parameters have to be bound before assertion resolution, the complexity of resolving assertions become much lower as every assertion parameter can be resolved independently.
+That is, by utilizing information from higher up the expression tree for return value overloading, most of the type bindings can be resolved.
+However, there are scenarios where some intermediate types need to be involved in certain operations, which are neither input nor output types.
 
-\CFA standard library provides a few polymorphic container types similar to those found in \CC standard template library. Naturally, we would like to have a harmonized iterator interface for different container types. The feature is still under development and has not been finalized, but for the purpose of this discussion, we will be using a similar approach to the \CC standard iterator contract. The equivalent type signatures can be given in \CFA trait as:
+\CFA standard library provides a few polymorphic container types similar to those found in the \CC standard library.
+Like \CC, \CFA would like to have a harmonized iterator interface for different container types.
+While this feature is still under development, the following trait outline is used to present the problem.
+\begin{cfa}
+forall( Container, Elem, Iter ) trait iterable {
+	@Iter@ begin( Container );
+	@Iter@ end( Container );
+	@Elem@ & *?( Iter );
+	Iter ++?( Iter );
+	bool ?==?( Iter, Iter );
+};
+\end{cfa}
+These are the \CC operators required for for-loop comprehension, \eg @for (Elem & e : container)@.
+Note, the iterable trait is meant to describe a property for a container type, but involves two additional types, one for the element type and one for the iterator type.
+However, @Iter@ is intended to be deduced from the @begin@ and @end@ operations on the container type;
+the same can be said for the element type @Elem@.
+The alternative is to make @Elem@ and @Iter@ unbound type-parameters by removing them from the @forall@.
+As mentioned, unbound type-parameters cause problems, but that is the only way to describe the iterable property.
 
+To solve this problem, I propose adding associate-type declarations in addition to the existing unbounded @forall@ type parameter.
+In the body of a trait declaration, new types can be introduced as the return type of an expression involving type parameters.
 \begin{cfa}
-    forall (Container, Iter, Elem) trait iterable {
-        Iter begin(Container);
-        Iter end(Container);
-        Elem& *?(Iter);
-        Iter ++?(Iter);
-        bool ?==?(Iter,Iter);
-    }
+forall( Container ) trait iterable {
+	@type@ Iter begin( Container );
+	Iter end( Container );
+	@type@ Elem & *?( Iter );
+	Iter ++?( Iter );
+	bool ?==?( Iter, Iter );
+};
 \end{cfa}
+This matches conceptually with the iterable trait having only the container type, rather than three types.
+The iterator type and element type are now viewed as properties of the container type not independent type parameters.
 
-These are the exact operators required in \CC for the for-loop comprehension
-@for (Elem & e: container)@. The problem with this trait declaration is that the iterator type @Iter@ has to be explicitly given in the trait parameter list, but is intended to be deduced from the @begin@ and @end@ operations on the container type; and the same can be said for the element type. The iterable trait is meant to describe a property for the container type but involves two additional types, one for the iterator type and one for the element type. If we were to disallow unbound type parameters in assertions without adding any features to the type system, we will not be able to describe this iterable property in \CFA. 
+There remains one design decision to be made: whether the expression that defines an associated type needs to be uniquely resolved.
+If the associated type does not appear in the parameter or return types, this requirement seems reasonable.
+The reason is that the expression cost does not consider any conversions that occur in assertion parameter matching, which essentially means having multiple ways to resolve an associated type always results in ambiguity.
+The interesting case is when the associated type also appears in the return type, where both resolving the return type overload based on context and resolving the assertion that defines the associate type can help;
+for the whole expression to resolve, they must agree on a common result.
 
-To solve this problem, I propose adding associate type declarations in addition to the existing (free) @forall@ type parameters. In the body of a trait declaration, new types can be introduced as the return type of an expression involving the type parameters. Following the above example, the iterator contract could be rewritten to
+Moss gave the following example to illustrate \CFA assertion system's expressiveness.
 \begin{cfa}
-    forall (Container) trait iterable {
-        type Iter = begin(Container);
-        type Elem& = *?(Iter);
-        Iter end(Container);
-        Iter ++?(Iter);
-        bool ?==?(Iter,Iter);
-    }
+forall( Ptr, Elem ) trait pointer_like {
+	Elem & *?( Ptr ); // Ptr can be dereferenced to Elem
+};
+struct list {
+	int value;
+	list * next;
+};
+typedef list * list_iterator;
+int & *?( list_iterator it ) {
+	return it->value;
+}
 \end{cfa}
+This can be viewed as having an associated type, @Elem@, as return, which can potentially vary based on context.
+Note that the type @list *@ satisfies both @pointer_like( list *, int )@ and @pointer_like( list *,@ @list )@ (the latter by the built-in pointer dereference operator) and the expression @*it@ can be either a @struct list@ or an @int@.
+Requiring associated types to be unique makes the @pointer_like@ trait not applicable to @list *@, which is undesirable.
+I have not attempted to implement associated types in \CFA compiler, but based on the above discussions, one option is to make associated type resolution and return type overloading coexist:
+when the associated type appears in returns, it is deduced from the context and then verify the trait with ordinary assertion resolution;
+when it does not appear in the returns, the type is required to be uniquely determined by the expression that defines the associated type.
 
-This matches conceptually better that the iterable trait is about one type (the container) rather than about three types. The iterator type and element type can be viewed as properties of the container types, not independent type parameters.
-
-There remains one design decision to be made, that is whether the expressions that define associated types need to be uniquely resolved. If the associated type does not appear in parameter or return types, having such requirement seems to be reasonable, because the expression cost does not consider any conversions that occur in assertion parameter matching, which essentially means having multiple ways to resolve an associated type always results in ambiguity. A more interesting case would be that the associated type also appears in the return type, where both resolving the return type overload based on context and resolving the assertion that defines the associate type can help, and for the whole expression to resolve, they must agree on a common result. Moss gave the following example to illustrate \CFA assertion system's expressiveness that could be viewed as having an associated type as return, and can potentially vary based on the context:
-
-\begin{cfa}
-    forall(Ptr, Elem) trait pointer_like {
-        Elem& *?(Ptr); // Ptr can be dereferenced to Elem
-    };
-    struct list {
-        int value;
-        list* next; // may omit struct on type names
-    };
-    typedef list* list_iterator;
-    int& *?(list_iterator it) {
-        return it->value;
-    }
-\end{cfa}
-
-Note that the type @list*@ satisfies both @pointer_like(list*, int)@ and @pointer_like(list*, list)@ (the latter by the built-in pointer dereference operator) and the expression @*it@ could be either a @struct list@ or an @int@. Requiring associated types to be unique would make the @pointer_like@ trait inapplicable to @list*@ here, which is not desirable. I have not attempted to implement associated types in \CFA compiler, but based on the above discussions, one option could be to make associated type resolution and return type overloading coexist: when the associated type appears in the returns, we deduce it from the context and then verify the trait with ordinary assertion resolution; when it does not appear in the returns, we instead require the type to be uniquely determined by the expression that defines the associated type.
 
 \section{User-defined conversions}
+
+Missing type-system feature is a scheme for user-defined conversions.
+Conversion means one type goes through an arbitrary complex process of changing its value to some meaningful value in another type.
+Because the conversion process can be arbitrarily complex, it requires the power of a function.
+Arbitrary conversions are already possible through standalone named functions.
+\begin{cfa}
+S convert( T );  $\C[2in]{// change T to S}$
+S s;   T t;
+s = convert( t );
+\end{cfa}
+C has implicit/explicit conversions for the builtin types.
+\begin{cfa}
+int i = 3.5;  $\C{// implicit, change the floating-point bits to integral bits}$
+int i = (int)3.5 + 17;  $\C{// explicit, change the floating-point bits to integral bits}$
+\end{cfa}
+When the conversion occurs in expression evaluation can significantly affect the result, where function call has higher precedence than cast.
+Overloading the cast operator would allow user-defined conversions to look and feel, like regular C casts, as is provided in \CC.
+\begin{cfa}[escapechar={}]
+S ?@$@( T ) { /* change T to S */ }
+s = t;
+\end{cfa}
+% $ stop formatting
+Similarly, constructors can be used for implicit conversion, as in \CC.
+\begin{cfa}
+void ?{}( S s, T t ) { ... } $\C{// convert T to S}$
+s = t;  $\C{// rewritten as s = ?{}( s, t )}\CRT$
+\end{cfa}
+To integrate properly with the \CFA conversion model, there would need to distinguish between safe and unsafe conversion, and possibly a way to denote conversions as explicit-only or non-chainable, otherwise conversion cycles are possible.
Index: doc/theses/fangren_yu_MMath/glossary.tex
===================================================================
--- doc/theses/fangren_yu_MMath/glossary.tex	(revision 7d405eb2bce8247558b6173cc06a2d68843eb9e2)
+++ 	(revision )
@@ -1,47 +1,0 @@
-% % Main glossary entries -- definitions of relevant terminology
-% \newglossaryentry{computer}
-% {
-% name=computer,
-% description={A programmable machine that receives input data,
-%                stores and manipulates the data, and provides
-%                formatted output}
-% }
-
-% % Nomenclature glossary entries -- New definitions, or unusual terminology
-% \newglossary*{nomenclature}{Nomenclature}
-% \newglossaryentry{dingledorf}
-% {
-% type=nomenclature,
-% name=dingledorf,
-% description={A person of supposed average intelligence who makes incredibly brainless misjudgments}
-% }
-
-% % List of Abbreviations (abbreviations type is built in to the glossaries-extra package)
-% \newabbreviation{aaaaz}{AAAAZ}{American Association of Amateur Astronomers and Zoologists}
-
-% % List of Symbols
-% \newglossary*{symbols}{List of Symbols}
-% \newglossaryentry{rvec}
-% {
-% name={$\mathbf{v}$},
-% sort={label},
-% type=symbols,
-% description={Random vector: a location in n-dimensional Cartesian space, where each dimensional component is determined by a random process}
-% }
-
-% Examples from template above
-
-\newabbreviation{foo}{FOO}{\Newterm{Fred Orders Oysters}}
-\newabbreviation{bar}{BAR}{\Newterm{Boys Are Rushed}}
-
-\newglossaryentry{git}{
-name=git,
-first={\Newterm{git}},
-description={is a system that can count the change in your pocket.}
-}
-
-\newglossaryentry{gulp}{
-name={gulp},
-first={\Newterm{gulp}},
-description={a motion made with the mouth.}
-}
Index: doc/theses/fangren_yu_MMath/resolution.tex
===================================================================
--- doc/theses/fangren_yu_MMath/resolution.tex	(revision 7d405eb2bce8247558b6173cc06a2d68843eb9e2)
+++ doc/theses/fangren_yu_MMath/resolution.tex	(revision 9fbc40e8adba86ceb318d8df9a796655673cfd4a)
@@ -478,4 +478,5 @@
 
 \section{Assertion Satisfaction}
+\label{s:AssertionSatisfaction}
 
 The assertion-satisfaction problem greatly increases the complexity of \CFA expression resolution.
