Index: doc/proposals/enum.tex
===================================================================
--- doc/proposals/enum.tex	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
+++ doc/proposals/enum.tex	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -0,0 +1,313 @@
+%%
+%% This is file `sample-manuscript.tex',
+%% generated with the docstrip utility.
+%%
+%% The original source files were:
+%%
+%% samples.dtx  (with options: `manuscript')
+%% 
+%% IMPORTANT NOTICE:
+%% 
+%% For the copyright see the source file.
+%% 
+%% Any modified versions of this file must be renamed
+%% with new filenames distinct from sample-manuscript.tex.
+%% 
+%% For distribution of the original source see the terms
+%% for copying and modification in the file samples.dtx.
+%% 
+%% This generated file may be distributed as long as the
+%% original source files, as listed above, are part of the
+%% same distribution. (The sources need not necessarily be
+%% in the same archive or directory.)
+%%
+%% Commands for TeXCount
+%TC:macro \cite [option:text,text]
+%TC:macro \citep [option:text,text]
+%TC:macro \citet [option:text,text]
+%TC:envir table 0 1
+%TC:envir table* 0 1
+%TC:envir tabular [ignore] word
+%TC:envir displaymath 0 word
+%TC:envir math 0 word
+%TC:envir comment 0 0
+%%
+%%
+%% The first command in your LaTeX source must be the \documentclass command.
+\documentclass[manuscript,screen,review]{acmart}
+\usepackage{xcolor}
+\usepackage{listings}
+\usepackage[ligature, inference]{semantic}
+\usepackage{array}
+
+\definecolor{mGreen}{rgb}{0,0.6,0}
+\definecolor{mGray}{rgb}{0.5,0.5,0.5}
+\definecolor{mPurple}{rgb}{0.58,0,0.82}
+\definecolor{backgroundColour}{rgb}{0.95,0.95,0.92}
+
+\lstdefinestyle{CStyle}{
+    backgroundcolor=\color{backgroundColour},   
+    commentstyle=\color{mGreen},
+    keywordstyle=\color{magenta},
+    numberstyle=\tiny\color{mGray},
+    stringstyle=\color{mPurple},
+    basicstyle=\footnotesize,
+    breakatwhitespace=false,         
+    breaklines=true,                 
+    captionpos=b,                    
+    keepspaces=true,                 
+    numbers=left,                    
+    numbersep=5pt,                  
+    showspaces=false,                
+    showstringspaces=false,
+    showtabs=false,                  
+    tabsize=2,
+    language=C
+}
+
+%%
+%% \BibTeX command to typeset BibTeX logo in the docs
+\AtBeginDocument{%
+  \providecommand\BibTeX{{%
+    \normalfont B\kern-0.5em{\scshape i\kern-0.25em b}\kern-0.8em\TeX}}}
+
+
+%%
+%% end of the preamble, start of the body of the document source.
+\begin{document}
+
+%%
+%% The "title" command has an optional parameter,
+%% allowing the author to define a "short title" to be used in page headers.
+\title{Enumeration in Cforall}
+
+%%
+%% The "author" command and its associated commands are used to define
+%% the authors and their affiliations.
+%% Of note is the shared affiliation of the first two authors, and the
+%% "authornote" and "authornotemark" commands
+%% used to denote shared contribution to the research.
+\author{Jiada Liang}
+
+
+%%
+%% The abstract is a short summary of the work to be presented in the
+%% article.
+\begin{abstract}
+    An enumeration, or enum in short, is a type that defines a list of named constant values in C. C uses integral type as the underlying representation of enum. Cforall extends C enum to allow more types, including custom types, to be used as enumeration inner representation.
+\end{abstract}
+
+%%
+%% The code below is generated by the tool at http://dl.acm.org/ccs.cfm.
+%% Please copy and paste the code instead of the example below.
+%%
+
+
+%%
+%% This command processes the author and affiliation and title
+%% information and builds the first part of the formatted document.
+\maketitle
+
+\section{C-Style Enum}
+\begin{lstlisting}[style=CStyle, label{lst:weekday}]
+enum Weekday { Monday, Tuesday, Wednesday, Thursday=10, Friday, Saturday, Sunday };
+\end{lstlisting}
+Cforall supports the C-Style enumeration (C-enum for short). It has the same syntax as C and resembles the same language semantics. In code~\ref{lst:weekday} example, the syntax defines an enum class $Weekday$ with enumerators $Monday$, $Tuesday$, $Wednesday$, $Thursday$, $Friday$, $Saturday$ and $Sunday$ in order. The successor of $Tuesday$ is $Monday$ and the predecessor of $Tuesday$ is $Wednesday$. Enumerators have an integral type, either being explicitly initialized by an initializer or being assigned a value by the compiler. For example, $Thursday$ has been assigned with value $10$. If not explicitly initialized, the first value of an enum, $Monday$ in the $Weekday$ example, has the integer value 0. Other uninitialized enum value has a value that is equal to their successor $+ 1$. The enum value $Tuesday$, $Wednesday$, $Friday$, $Saturday$, and $Sunday$ have value 1, 2, 11, 12, and 13 respectively. 
+
+\begin{lstlisting}[label{lst:enum_scope}, style=CStyle]
+{
+    {
+        enum RGB {R, G, B};
+        int i = R  // i == 0
+    }
+    int j = G; // ERROR! G is not declared in this scope
+}
+\end{lstlisting}
+C-enums are unscoped: enumerators declared inside of an enum are visible in the enclosing scope of the enum class.
+
+\section{Cforall-Style Enum}
+\begin{lstlisting}[style=CStyle, label{lst:color}]
+enum Color(char *) { Red="R", Green="G", Blue="B"  };
+\end{lstlisting}
+A Cforall enumeration is parameterized by a type declared. Cforall allows any oType in the enum declaration, and values assigned to enumerators must be in the declared type.
+
+\section{Enumerable Type Traits}
+A trait is a collection of constraints in Cforall, which can be used to describe types. Cforall standard library defines traits to categorize types that are related enumeration features.
+\subsection{Enumerable}
+A type is enumerable if it can map an integer to a value. 
+\begin{lstlisting}[style=CStyle]
+forall(T)
+trait Enumerable {
+    T value( *class_name* , int );
+};
+\end{lstlisting}
+The parameter class name stands for the name of an enumeration class, Weekday, for example.
+
+\subsection{AutoInitializable}
+\begin{lstlisting}[style=CStyle]
+forall(T)
+trait AutoInitializable {
+  void ?()( T & t, zero_t );
+  void ?()( T & t, one_t );
+  S& ?+=?( T & t, one_t );
+  void ?{}( T &, T ); 
+  T ?{}( T &, T ); 
+};
+\end{lstlisting}
+
+\subsection{AutoInitializable}
+\begin{lstlisting}[style=CStyle]
+forall(T)
+trait AutoInitializable {
+  void ?()( T & t, zero_t );
+  void ?()( T & t, one_t );
+  S& ?+=?( T & t, one_t );
+  void ?{}( T &, T ); 
+  T ?{}( T &, T ); 
+};
+\end{lstlisting}
+A type is AutoInitializable if it has defined a zero\_t constructor, a one\_t constructor, an addition assignment operator, a copy constructor, and a copy assignment operator.
+
+\subsection{Enumerable Type}
+\begin{lstlisting}[style=CStyle]
+forall(T)
+trait enumerable {
+  void ?()( T & t, zero_t );
+  void ?()( T & t, one_t );
+  S& ?+=?( T & t, one_t );
+  void ?{}( T &, T ); 
+  T ?{}( T &, T ); 
+};
+\end{lstlisting}
+
+
+
+
+
+(Should change the definition of enumerable to something else. Maybe auto-constructible. If a type is not auto-constructible, all enumeration must be explicitly initialized)
+\begin{lstlisting}[caption={An example enumerable type}, label{lst:sample_enumerable}, style=CStyle]
+struct Type { int i; };
+void ?()( Type & t, zero_t ) { t.i = 0; };
+void ?()( Type & t, one_t ) { t.i = 1; };
+int ?!=?( Type t, zero_t ) { return t.i != 0; };
+S& ?+=?( Type & t, one_t ) { t.i += 1; return t; };
+void ?()( Type & t, Type rhs ) { t.i = rhs.i; };
+Type ?()( Type & t, Type rhs ) { t.i = rhs.i; return t; };
+\end{lstlisting}
+
+A Cforall-enum is a C-enum parameterized by an enumerable type. For example,  $enum(int)$ turns a C-enum into a Cforall-enum.
+\begin{lstlisting}[caption={An example Cforall enum}, label{lst:sample_cforall_enum}, style=CStyle]
+enum Color(Type) { Red, Green, Blue };
+
+> Type Color.values[] = { 0, values[0]++, values[1]++ }; 
+> enum Color.Label { Red_Label, Green_Label, Blue_Label };
+\end{lstlisting}
+Declaring a Cforall-enum, the compiler defines a C-enum names every element in the Cforall-enum, and an array that stores Cforall enumeration values. 
+
+\subsection{Cforall Enumerations Behaviour}
+An instance of Cforall-enum (denoted as $<enum\_instance>$) has a label, the defined enum name. The label can be retrieved by calling the function $label()$ on a $<enum\_instance>$. The $value()$ function on the other hand returns the value used to initialize the Cforall-enum.
+
+Cforall-enum supports a qualified expression. The syntax of the qualified expression for Cforall-enum is $$<enum\_type\_name>.<enum\_instance\_name>$$. In the $Color$ example, $Color$ is a $<enum\_type\_name>$ and $Red$, $Green$, $Blue$ are $<enum\_instance\_name>$. 
+
+\begin{lstlisting}[caption={An example Cforall enum}, label{lst:sample_cforall_enum_usage}, style=CStyle]
+enum Color red = Color.Red;
+> enum Color.Label red = = Color.Label.Red_Label; 
+Type instance = Color.Red;
+> Type instance = Color.values[ Color.Label.Red_Label ];
+\end{lstlisting}
+
+The expression $Color.Red$ is overloaded to represent both $value(Color.Red)$ and $label(Color.Red)$. The expression returns the $label(Color.Red)$ by default but returns $value()$ whenever the $value()$ is a closer candidate in the context. [more explanation] In \ref{lst:sample_cforall_enum_usage}, when assigned to an enum variable, $Color.Red$ returns the label. This is to reduce the memory to store a Cforall-enum variable. In an assignment expression when the left-hand-side expects a $Type$, the resolution finds $value(Color.Red)$ is a better candidate than $label(Color.Red)$, and returns the value instead.
+
+\subsection{Enum Type Functions}
+\begin{lstlisting}[caption={Enum Type Functions}, label{lst:cforall_enum_functions}, style=CStyle]
+enum Color(string) { // assume String has been defined as an enumerable type
+    R = "Red", G = "Green", B = "Blue"
+};
+values( Color );
+> [ String("Red"), String("Green"), String("Blue") ];
+label_strings( Color );
+> [ "R", "G", "B" ];
+enum Color green = Color.G;
+
+label_string( Color, green );
+> "G"
+label( Color, green );
+> 1
+value( Color, green ) ;
+> "Green"
+value( Color, "G" );
+> "Green"
+label( Color, "G" );
+> 1
+value( Color, "DNE" );
+> (null)
+value( Color, 1 ); // "1" is the label "G"
+> "Green"
+\end{lstlisting}
+Names of labels are distinct in an enum declaration. Cforall therefore allows indexing an enum value with its string representation of a label.
+
+\subsection{Iteration and Range}
+A Cforall enum is iterable and supports range function.
+\begin{lstlisting}[caption={Range Functions}, label{lst:range_functions}, style=CStyle]
+struct string;
+enum(string) Weekday( 
+    Monday = "M", Tuesday = "Tu", ...
+};
+for ( i; Weekday ) { sout | i; }
+>> M Tu W Th F Sat Sun
+for ( Monday ~= Tuesday )
+>> M Tu
+\end{lstlisting}
+
+\section{Implementation}
+
+\subsection{Companion Object}
+The intuition to create a companion object is that functions that support enumeration features need static information of an enumeration class. For example, values() returns an array of values defined for the enumeration. $label( Color, "G" )$ needs information about enum names defined for the enum class $Color$. Theoretically, enum-type functions can be defined as functions that take $TypeName$ expression as the first parameter. An alternative approach is to define that "companion object".
+
+\begin{lstlisting}[caption={Enum Type Functions}, label{lst:cforall_enum_functions}, style=CStyle]
+struct string;
+enum Color( string ) { 
+    R = "Red", G = "Green", B = "Blue"
+};
+
+forall( T | enumerable(T) )  {
+    struct Companion {
+        T* values;
+        char** labels;
+    };
+}
+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+enum Color.Label;
+Companion( string ) Color = { 
+    .values = [ "Red", "Green", "Blue" ],
+    .labels = [ "R", "G", "B" ]
+};
+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+forall( T | enumerable(T) )
+T value( Companion companion, int index ) { return companion.values[ index ]; } 
+T value( Companion, enum Color.Label );
+char* label( Companion companion, int index ) { return companion.values[ index ]; }
+char* label( Companion, enum Color.Label );
+
+\end{lstlisting}
+
+
+\subsection{Companion Trait}
+Users can define the companion object themselves. A companion object should define an array of any type called values and an array of strings representing a label. Defining a companion object effectively creates a new enumerable type. 
+
+\subsection{Companion Mapping}
+
+
+
+\begin{lstlisting}[caption={Enum Type Functions}, label{lst:cforall_enum_functions}, style=CStyle]
+
+\end{lstlisting}
+%%
+%% If your work has an appendix, this is the place to put it.
+\appendix
+
+
+\end{document}
+\endinput
+%%
+%% End of file `sample-manuscript.tex'.
Index: c/theses/jiada_liang_MMath/main.tex
===================================================================
--- doc/theses/jiada_liang_MMath/main.tex	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ 	(revision )
@@ -1,270 +1,0 @@
-%%
-%% This is file `sample-manuscript.tex',
-%% generated with the docstrip utility.
-%%
-%% The original source files were:
-%%
-%% samples.dtx  (with options: `manuscript')
-%% 
-%% IMPORTANT NOTICE:
-%% 
-%% For the copyright see the source file.
-%% 
-%% Any modified versions of this file must be renamed
-%% with new filenames distinct from sample-manuscript.tex.
-%% 
-%% For distribution of the original source see the terms
-%% for copying and modification in the file samples.dtx.
-%% 
-%% This generated file may be distributed as long as the
-%% original source files, as listed above, are part of the
-%% same distribution. (The sources need not necessarily be
-%% in the same archive or directory.)
-%%
-%% Commands for TeXCount
-%TC:macro \cite [option:text,text]
-%TC:macro \citep [option:text,text]
-%TC:macro \citet [option:text,text]
-%TC:envir table 0 1
-%TC:envir table* 0 1
-%TC:envir tabular [ignore] word
-%TC:envir displaymath 0 word
-%TC:envir math 0 word
-%TC:envir comment 0 0
-%%
-%%
-%% The first command in your LaTeX source must be the \documentclass command.
-\documentclass[manuscript,screen,review]{acmart}
-\usepackage{xcolor}
-\usepackage{listings}
-\usepackage[ligature, inference]{semantic}
-\usepackage{array}
-
-\definecolor{mGreen}{rgb}{0,0.6,0}
-\definecolor{mGray}{rgb}{0.5,0.5,0.5}
-\definecolor{mPurple}{rgb}{0.58,0,0.82}
-\definecolor{backgroundColour}{rgb}{0.95,0.95,0.92}
-
-\lstdefinestyle{CStyle}{
-    backgroundcolor=\color{backgroundColour},   
-    commentstyle=\color{mGreen},
-    keywordstyle=\color{magenta},
-    numberstyle=\tiny\color{mGray},
-    stringstyle=\color{mPurple},
-    basicstyle=\footnotesize,
-    breakatwhitespace=false,         
-    breaklines=true,                 
-    captionpos=b,                    
-    keepspaces=true,                 
-    numbers=left,                    
-    numbersep=5pt,                  
-    showspaces=false,                
-    showstringspaces=false,
-    showtabs=false,                  
-    tabsize=2,
-    language=C
-}
-
-%%
-%% \BibTeX command to typeset BibTeX logo in the docs
-\AtBeginDocument{%
-  \providecommand\BibTeX{{%
-    \normalfont B\kern-0.5em{\scshape i\kern-0.25em b}\kern-0.8em\TeX}}}
-
-
-
-%%
-%% Submission ID.
-%% Use this when submitting an article to a sponsored event. You'll
-%% receive a unique submission ID from the organizers
-%% of the event, and this ID should be used as the parameter to this command.
-%%\acmSubmissionID{123-A56-BU3}
-
-%%
-%% For managing citations, it is recommended to use bibliography
-%% files in BibTeX format.
-%%
-%% You can then either use BibTeX with the ACM-Reference-Format style,
-%% or BibLaTeX with the acmnumeric or acmauthoryear sytles, that include
-%% support for advanced citation of software artefact from the
-%% biblatex-software package, also separately available on CTAN.
-%%
-%% Look at the sample-*-biblatex.tex files for templates showcasing
-%% the biblatex styles.
-%%
-
-%%
-%% The majority of ACM publications use numbered citations and
-%% references.  The command \citestyle{authoryear} switches to the
-%% "author year" style.
-%%
-%% If you are preparing content for an event
-%% sponsored by ACM SIGGRAPH, you must use the "author year" style of
-%% citations and references.
-%% Uncommenting
-%% the next command will enable that style.
-%%\citestyle{acmauthoryear}
-
-%%
-%% end of the preamble, start of the body of the document source.
-\begin{document}
-
-%%
-%% The "title" command has an optional parameter,
-%% allowing the author to define a "short title" to be used in page headers.
-\title{Enumeration in Cforall}
-
-%%
-%% The "author" command and its associated commands are used to define
-%% the authors and their affiliations.
-%% Of note is the shared affiliation of the first two authors, and the
-%% "authornote" and "authornotemark" commands
-%% used to denote shared contribution to the research.
-\author{Jiada Liang}
-
-
-%%
-%% The abstract is a short summary of the work to be presented in the
-%% article.
-\begin{abstract}
-    An enumeration, or enum in short, is a type that defines a list of named constant values in C. Cforall extends the enumeration with additional features.
-\end{abstract}
-
-%%
-%% The code below is generated by the tool at http://dl.acm.org/ccs.cfm.
-%% Please copy and paste the code instead of the example below.
-%%
-
-
-%%
-%% This command processes the author and affiliation and title
-%% information and builds the first part of the formatted document.
-\maketitle
-
-\section{C-Style Enum}
-\begin{lstlisting}[style=CStyle]
-enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
-\end{lstlisting}
-Cforall supports the classic C-Style enumeration (C-enum for short) and its syntax is consistent with C. No internal data structure is generated for C-enum, and C-enum does not provide the Cforall-enum interface methods.
-
-\section{Cforall Enum}
-\subsection{Enumerable Type}
-\begin{lstlisting}[style=CStyle]
-forall(T)
-trait enumerable {
-  void ?()( T & t, zero_t );
-  void ?()( T & t, one_t );
-  S& ?+=?( T & t, one_t );
-  void ?{}( T &, T ); 
-  T ?{}( T &, T ); 
-};
-\end{lstlisting}
-A type is enumerable in Cforall if it has defined 0, 1, increment operator, copy constructor, and copy assignment operator.
-
-(Should change the definition of enumerable to something else. Maybe auto-constructible. If a type is not auto-constructible, all enumeration must be explicitly initialized)
-\begin{lstlisting}[caption={An example enumerable type}, label{lst:sample_enumerable}, style=CStyle]
-struct Type { int i; };
-void ?()( Type & t, zero_t ) { t.i = 0; };
-void ?()( Type & t, one_t ) { t.i = 1; };
-int ?!=?( Type t, zero_t ) { return t.i != 0; };
-S& ?+=?( Type & t, one_t ) { t.i += 1; return t; };
-void ?()( Type & t, Type rhs ) { t.i = rhs.i; };
-Type ?()( Type & t, Type rhs ) { t.i = rhs.i; return t; };
-\end{lstlisting}
-
-A Cforall-enum is a C-enum parameterized by an enumerable type. For example,  $enum(int)$ turns a C-enum into a Cforall-enum.
-\begin{lstlisting}[caption={An example Cforall enum}, label{lst:sample_cforall_enum}, style=CStyle]
-enum Color(Type) { Red, Green, Blue };
-
-> Type Color.values[] = { 0, values[0]++, values[1]++ }; 
-> enum Color.Label { Red_Label, Green_Label, Blue_Label };
-\end{lstlisting}
-Declaring a Cforall-enum, the compiler defines a C-enum names every element in the Cforall-enum, and an array that stores Cforall enumeration values. 
-
-\subsection{Cforall Enumerations Behaviour}
-An instance of Cforall-enum (denoted as $<enum\_instance>$) has a label, the defined enum name. The label can be retrieved by calling the function $label()$ on a $<enum\_instance>$. The $value()$ function on the other hand returns the value used to initialize the Cforall-enum.
-
-Cforall-enum supports a qualified expression. The syntax of the qualified expression for Cforall-enum is $$<enum\_type\_name>.<enum\_instance\_name>$$. In the $Color$ example, $Color$ is a $<enum\_type\_name>$ and $Red$, $Green$, $Blue$ are $<enum\_instance\_name>$. 
-
-\begin{lstlisting}[caption={An example Cforall enum}, label{lst:sample_cforall_enum_usage}, style=CStyle]
-enum Color red = Color.Red;
-> enum Color.Label red = = Color.Label.Red_Label; 
-Type instance = Color.Red;
-> Type instance = Color.values[ Color.Label.Red_Label ];
-\end{lstlisting}
-
-The expression $Color.Red$ is overloaded to represent both $value(Color.Red)$ and $label(Color.Red)$. The expression returns the $label(Color.Red)$ by default but returns $value()$ whenever the $value()$ is a closer candidate in the context. [more explanation] In \ref{lst:sample_cforall_enum_usage}, when assigned to an enum variable, $Color.Red$ returns the label. This is to reduce the memory to store a Cforall-enum variable. In an assignment expression when the left-hand-side expects a $Type$, the resolution finds $value(Color.Red)$ is a better candidate than $label(Color.Red)$, and returns the value instead.
-
-\subsection{Enum Type Functions}
-\begin{lstlisting}[caption={Enum Type Functions}, label{lst:cforall_enum_functions}, style=CStyle]
-enum Color(string) { // assume String has been defined as an enumerable type
-    R = "Red", G = "Green", B = "Blue"
-};
-values( Color );
-> [ String("Red"), String("Green"), String("Blue") ];
-label_strings( Color );
-> [ "R", "G", "B" ];
-enum Color green = Color.G;
-
-label_string( Color, green );
-> "G"
-label( Color, green );
-> 1
-value( Color, green ) ;
-> "Green"
-value( Color, "G" );
-> "Green"
-label( Color, "G" );
-> 1
-value( Color, "DNE" );
-> (null)
-value( Color, 1 ); // "1" is the label "G"
-> "Green"
-\end{lstlisting}
-Names of labels are distinct in an enum declaration. Cforall therefore allows indexing an enum value with its string representation of a label.
-
-\subsection{Range Functions and Iteration (Placeholder)}
-\begin{lstlisting}[caption={Range Functions}, label{lst:range_functions}, style=CStyle]
-enum Weekday( 
-    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
-};
-\end{lstlisting}
-
-\section{Implementation}
-
-\subsection{Companion Object}
-The intuition to create a companion object is that functions that support enumeration features need static information of an enumeration class. For example, values() returns an array of values defined for the enumeration. $label( Color, "G" )$ needs information about enum names defined for the enum class $Color$. Theoretically, enum-type functions can be defined as functions that take $TypeName$ expression as the first parameter. An alternative approach is to define that "companion object".
-
-\begin{lstlisting}[caption={Enum Type Functions}, label{lst:cforall_enum_functions}, style=CStyle]
-struct string;
-enum Color( string ) { 
-    R = "Red", G = "Green", B = "Blue"
-};
-
-forall( T | enumerable(T) )  {
-    struct Companion {
-        T* values;
-        char** labels;
-    };
-}
->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-Companion( string ) Color = { 
-    .values = [ "Red", "Green", "Blue" ],
-    .labels = [ "R", "G", "B" ]
-};
->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-forall( T | enumerable(T) )
-T* value( Companion, int );
-char* label( Companion, int );
-\end{lstlisting}
-
-\subsection{TODO - Type trait for Cforall - Enum}
-%%
-%% If your work has an appendix, this is the place to put it.
-\appendix
-
-
-\end{document}
-\endinput
-%%
-%% End of file `sample-manuscript.tex'.
Index: src/CodeTools/DeclStats.cc
===================================================================
--- src/CodeTools/DeclStats.cc	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ src/CodeTools/DeclStats.cc	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -25,5 +25,4 @@
 #include "Common/PassVisitor.h"
 #include "Common/VectorMap.h"      // for VectorMap
-#include "GenPoly/GenPoly.h"       // for hasPolyBase
 #include "SynTree/LinkageSpec.h"   // for ::NoOfSpecs, Spec
 #include "SynTree/Declaration.h"   // for FunctionDecl, TypeDecl, Declaration
Index: src/GenPoly/BoxNew.cpp
===================================================================
--- src/GenPoly/BoxNew.cpp	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ src/GenPoly/BoxNew.cpp	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -39,10 +39,4 @@
 
 namespace {
-
-/// Common field of several sub-passes of box.
-struct BoxPass {
-	TypeVarMap scopeTypeVars;
-	BoxPass() : scopeTypeVars( ast::TypeData() ) {}
-};
 
 // TODO: Could this be a common helper somewhere?
@@ -359,5 +353,4 @@
 /// * Adds appropriate type variables to the function calls.
 struct CallAdapter final :
-		public BoxPass,
 		public ast::WithConstTypeSubstitution,
 		public ast::WithGuards,
@@ -376,6 +369,4 @@
 	ast::Expr const * postvisit( ast::AddressExpr const * expr );
 	ast::ReturnStmt const * previsit( ast::ReturnStmt const * stmt );
-	void previsit( ast::PointerType const * type );
-	void previsit( ast::FunctionType const * type );
 
 	void beginScope();
@@ -386,16 +377,8 @@
 	// return value.
 
-	/// Pass the extra type parameters from polymorphic generic arguments or
-	/// return types into a function application.
-	ast::vector<ast::Expr>::iterator passArgTypeVars(
-		ast::ApplicationExpr * expr, ast::Type const * parmType,
-		ast::Type const * argBaseType, ast::vector<ast::Expr>::iterator arg,
-		const TypeVarMap & exprTyVars, std::set<std::string> & seenTypes );
-	/// Passes extra type parameters into a polymorphic function application.
+	/// Passes extra layout arguments for sized polymorphic type parameters.
 	ast::vector<ast::Expr>::iterator passTypeVars(
 		ast::ApplicationExpr * expr,
-		ast::Type const * polyRetType,
-		ast::FunctionType const * funcType,
-		const TypeVarMap & exprTyVars );
+		ast::FunctionType const * funcType );
 	/// Wraps a function application with a new temporary for the
 	/// out-parameter return value.
@@ -448,5 +431,5 @@
 		CodeLocation const & location, ast::Type const * type );
 
-	/// Set of adapter functions in the current scope.
+	TypeVarMap scopeTypeVars;
 	ScopedMap< std::string, ast::DeclWithType const * > adapters;
 	std::map< ast::ApplicationExpr const *, ast::Expr const * > retVals;
@@ -561,12 +544,11 @@
 
 ast::FunctionDecl const * CallAdapter::previsit( ast::FunctionDecl const * decl ) {
+	// Prevent type declaration information from leaking out.
+	GuardScope( scopeTypeVars );
+
 	if ( nullptr == decl->stmts ) {
-		// This may keep TypeDecls we don't ever want from sneaking in.
-		// Not visiting child nodes might just be faster.
-		GuardScope( scopeTypeVars );
 		return decl;
 	}
 
-	GuardScope( scopeTypeVars );
 	GuardValue( retval );
 
@@ -670,5 +652,5 @@
 	ptrdiff_t initArgCount = mutExpr->args.size();
 
-	TypeVarMap exprTypeVars = { ast::TypeData() };
+	TypeVarMap exprTypeVars;
 	// TODO: Should this take into account the variables already bound in
 	// scopeTypeVars ([ex] remove them from exprTypeVars)?
@@ -695,10 +677,6 @@
 
 	assert( typeSubs );
-	ast::Type const * concRetType = replaceWithConcrete( dynRetType, *typeSubs );
-	// Used to use dynRetType instead of concRetType; this changed so that
-	// the correct type parameters are passed for return types (it should be
-	// the concrete type's parameters, not the formal type's).
 	ast::vector<ast::Expr>::iterator argIt =
-		passTypeVars( mutExpr, concRetType, function, exprTypeVars );
+		passTypeVars( mutExpr, function );
 	addInferredParams( mutExpr, argIt, function, exprTypeVars );
 
@@ -778,14 +756,4 @@
 }
 
-void CallAdapter::previsit( ast::PointerType const * type ) {
-	GuardScope( scopeTypeVars );
-	makeTypeVarMap( type, scopeTypeVars );
-}
-
-void CallAdapter::previsit( ast::FunctionType const * type ) {
-	GuardScope( scopeTypeVars );
-	makeTypeVarMap( type, scopeTypeVars );
-}
-
 void CallAdapter::beginScope() {
 	adapters.beginScope();
@@ -812,54 +780,7 @@
 }
 
-// arg is an in/out parameter that matches the return value.
-ast::vector<ast::Expr>::iterator CallAdapter::passArgTypeVars(
-		ast::ApplicationExpr * expr, ast::Type const * paramType,
-		ast::Type const * argBaseType, ast::vector<ast::Expr>::iterator arg,
-		const TypeVarMap & exprTypeVars, std::set<std::string> & seenTypes ) {
-	ast::Type const * polyType = isPolyType( paramType, exprTypeVars );
-	if ( !polyType || dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
-		return arg;
-	}
-
-	std::string typeName = Mangle::mangleType( polyType );
-	if ( seenTypes.count( typeName ) ) return arg;
-
-	arg = expr->args.insert( arg,
-		new ast::SizeofExpr( expr->location, ast::deepCopy( argBaseType ) )
-	);
-	arg++;
-	arg = expr->args.insert( arg,
-		new ast::AlignofExpr( expr->location, ast::deepCopy( argBaseType ) )
-	);
-	arg++;
-	if ( dynamic_cast<ast::StructInstType const *>( polyType ) ) {
-		auto argBaseStructType =
-				dynamic_cast<ast::StructInstType const *>( argBaseType );
-		if ( nullptr == argBaseStructType ) {
-			SemanticError( expr,
-				"Cannot pass non-structure type for generic struct: " );
-		}
-
-		// Zero-length arrays are forbidden by C, so don't pass
-		// offset for empty structure.
-		if ( !argBaseStructType->base->members.empty() ) {
-			arg = expr->args.insert( arg,
-				new ast::OffsetPackExpr(
-					expr->location,
-					ast::deepCopy( argBaseStructType ) )
-			);
-			arg++;
-		}
-	}
-
-	seenTypes.insert( typeName );
-	return arg;
-}
-
 ast::vector<ast::Expr>::iterator CallAdapter::passTypeVars(
 		ast::ApplicationExpr * expr,
-		ast::Type const * polyRetType,
-		ast::FunctionType const * function,
-		const TypeVarMap & exprTypeVars ) {
+		ast::FunctionType const * function ) {
 	assert( typeSubs );
 	ast::vector<ast::Expr>::iterator arg = expr->args.begin();
@@ -880,46 +801,4 @@
 			new ast::AlignofExpr( expr->location, ast::deepCopy( concrete ) ) );
 		arg++;
-	}
-
-	// Add size/align for generic types to parameter list.
-	if ( !expr->func->result ) return arg;
-	ast::FunctionType const * funcType = getFunctionType( expr->func->result );
-	assert( funcType );
-
-	// This iterator points at first original argument.
-	ast::vector<ast::Expr>::const_iterator funcArg;
-	// Names for generic types we've seen.
-	std::set<std::string> seenTypes;
-
-	// A polymorphic return type may need to be added to the argument list.
-	if ( polyRetType ) {
-		assert( typeSubs );
-		auto concRetType = replaceWithConcrete( polyRetType, *typeSubs );
-		// TODO: This write-back may not be correct.
-		arg = passArgTypeVars( expr, polyRetType, concRetType,
-				arg, exprTypeVars, seenTypes );
-		// Skip the return parameter in the argument list.
-		funcArg = arg + 1;
-	} else {
-		funcArg = arg;
-	}
-
-	// TODO:
-	// I believe this is (starts as) the number of original arguments to the
-	// function with the args before funcArg all being inserted.
-	ptrdiff_t argsToPass = std::distance( funcArg, expr->args.cend() );
-
-	// Add type information args for presently unseen types in parameter list.
-	ast::vector<ast::Type>::const_iterator funcParam = funcType->params.begin();
-	// assert( funcType->params.size() == argsToPass );
-	for ( ; funcParam != funcType->params.end() && 0 < argsToPass
-			; ++funcParam, --argsToPass ) {
-		assert( 0 < argsToPass );
-		assert( argsToPass <= (ptrdiff_t)expr->args.size() );
-		ptrdiff_t index = expr->args.size() - argsToPass;
-		ast::Type const * argType = expr->args[index]->result;
-		if ( nullptr == argType ) continue;
-		arg = passArgTypeVars( expr, *funcParam, argType,
-				arg, exprTypeVars, seenTypes );
 	}
 	return arg;
@@ -1523,13 +1402,6 @@
 }
 
-ast::ObjectDecl * makePtr(
-		CodeLocation const & location, std::string const & name ) {
-	return new ast::ObjectDecl( location, name,
-		new ast::PointerType( makeSizeAlignType() ),
-		nullptr, ast::Storage::Classes(), ast::Linkage::C, nullptr );
-}
-
 ast::FunctionDecl const * DeclAdapter::previsit( ast::FunctionDecl const * decl ) {
-	TypeVarMap localTypeVars = { ast::TypeData() };
+	TypeVarMap localTypeVars;
 	makeTypeVarMap( decl, localTypeVars );
 
@@ -1584,36 +1456,7 @@
 	mutDecl->assertions.clear();
 
-	// Add size/align for generic parameter types to parameter list.
-	std::set<std::string> seenTypes;
-	ast::vector<ast::DeclWithType> otypeParams;
-	for ( ast::ptr<ast::DeclWithType> & funcParam : mutDecl->params ) {
-		ast::Type const * polyType = isPolyType( funcParam->get_type(), localTypeVars );
-		if ( !polyType || dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
-			continue;
-		}
-		std::string typeName = Mangle::mangleType( polyType );
-		if ( seenTypes.count( typeName ) ) continue;
-		seenTypes.insert( typeName );
-
-		auto sizeParam = makeObj( funcParam->location, sizeofName( typeName ) );
-		otypeParams.emplace_back( sizeParam );
-
-		auto alignParam = makeObj( funcParam->location, alignofName( typeName ) );
-		otypeParams.emplace_back( alignParam );
-
-		// Zero-length arrays are illegal in C, so empty structs have no
-		// offset array.
-		if ( auto * polyStruct =
-				dynamic_cast<ast::StructInstType const *>( polyType ) ;
-				polyStruct && !polyStruct->base->members.empty() ) {
-			auto offsetParam = makePtr( funcParam->location, offsetofName( typeName ) );
-			otypeParams.emplace_back( offsetParam );
-		}
-	}
-
 	// Prepend each argument group. From last group to first. addAdapters
 	// does do the same, it just does it itself and see all other parameters.
 	spliceBegin( mutDecl->params, inferredParams );
-	spliceBegin( mutDecl->params, otypeParams );
 	spliceBegin( mutDecl->params, layoutParams );
 	addAdapters( mutDecl, localTypeVars );
@@ -1708,5 +1551,4 @@
 	assertf( it != adapters.end(), "Could not correct floating node." );
 	return ast::mutate_field( expr, &ast::VariableExpr::var, it->second );
-
 }
 
@@ -1720,5 +1562,4 @@
 /// * Inserts dynamic calculation of polymorphic type layouts where needed.
 struct PolyGenericCalculator final :
-		public BoxPass,
 		public ast::WithConstTypeSubstitution,
 		public ast::WithDeclsToAdd<>,
@@ -1728,5 +1569,4 @@
 	PolyGenericCalculator();
 
-	void previsit( ast::ObjectDecl const * decl );
 	void previsit( ast::FunctionDecl const * decl );
 	void previsit( ast::TypedefDecl const * decl );
@@ -1735,6 +1575,4 @@
 	ast::StructDecl const * previsit( ast::StructDecl const * decl );
 	ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
-	void previsit( ast::PointerType const * type );
-	void previsit( ast::FunctionType const * type );
 	ast::DeclStmt const * previsit( ast::DeclStmt const * stmt );
 	ast::Expr const * postvisit( ast::MemberExpr const * expr );
@@ -1768,11 +1606,10 @@
 	/// C sizeof().
 	ast::Expr const * genSizeof( CodeLocation const &, ast::Type const * );
-
 	/// Enters a new scope for type-variables,
 	/// adding the type variables from the provided type.
 	void beginTypeScope( ast::Type const * );
-	/// Enters a new scope for known layouts and offsets, and queues exit calls.
-	void beginGenericScope();
-
+
+	/// The type variables and polymorphic parameters currently in scope.
+	TypeVarMap scopeTypeVars;
 	/// Set of generic type layouts known in the current scope,
 	/// indexed by sizeofName.
@@ -1785,6 +1622,4 @@
 	/// If the argument of an AddressExpr is MemberExpr, it is stored here.
 	ast::MemberExpr const * addrMember = nullptr;
-	/// Used to avoid recursing too deep in type declarations.
-	bool expect_func_type = false;
 };
 
@@ -1808,20 +1643,7 @@
 }
 
-void PolyGenericCalculator::previsit( ast::ObjectDecl const * decl ) {
+void PolyGenericCalculator::previsit( ast::FunctionDecl const * decl ) {
+	GuardScope( *this );
 	beginTypeScope( decl->type );
-}
-
-void PolyGenericCalculator::previsit( ast::FunctionDecl const * decl ) {
-	beginGenericScope();
-	beginTypeScope( decl->type );
-
-	// TODO: Going though dec->params does not work for some reason.
-	for ( ast::ptr<ast::Type> const & funcParam : decl->type->params ) {
-		// Condition here duplicates that in `DeclAdapter::previsit( FunctionDecl const * )`
-		ast::Type const * polyType = isPolyType( funcParam, scopeTypeVars );
-		if ( polyType && !dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
-			knownLayouts.insert( Mangle::mangleType( polyType ) );
-		}
-	}
 }
 
@@ -1838,5 +1660,5 @@
 		ast::TypeDecl const * decl ) {
 	ast::Type const * base = decl->base;
-	if ( nullptr == base) return decl;
+	if ( nullptr == base ) return decl;
 
 	// Add size/align variables for opaque type declarations.
@@ -1863,8 +1685,7 @@
 	alignDecl->accept( *visitor );
 
-	// Can't use [makeVar], because it inserts into stmtsToAdd and TypeDecls
-	// can occur at global scope.
+	// A little trick to replace this with two declarations.
+	// Adding after makes sure that there is no conflict with adding stmts.
 	declsToAddAfter.push_back( alignDecl );
-	// replace with sizeDecl.
 	return sizeDecl;
 }
@@ -1884,31 +1705,4 @@
 }
 
-void PolyGenericCalculator::previsit( ast::PointerType const * type ) {
-	beginTypeScope( type );
-}
-
-void PolyGenericCalculator::previsit( ast::FunctionType const * type ) {
-	beginTypeScope( type );
-
-	GuardValue( expect_func_type );
-	GuardScope( *this );
-
-	// The other functions type we will see in this scope are probably
-	// function parameters they don't help us with the layout and offsets so
-	// don't mark them as known in this scope.
-	expect_func_type = false;
-
-	// Make sure that any type information passed into the function is
-	// accounted for.
-	for ( ast::ptr<ast::Type> const & funcParam : type->params ) {
-		// Condition here duplicates that in `DeclAdapter::previsit( FunctionDecl const * )`
-		ast::Type const * polyType = isPolyType( funcParam, scopeTypeVars );
-		if ( polyType && !dynamic_cast<ast::TypeInstType const *>( polyType ) ) {
-			knownLayouts.insert( Mangle::mangleType( polyType ) );
-		}
-	}
-}
-
-//void PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
 ast::DeclStmt const * PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
 	ast::ObjectDecl const * decl = stmt->decl.as<ast::ObjectDecl>();
@@ -1918,6 +1712,5 @@
 
 	// Change initialization of a polymorphic value object to allocate via a
-	// variable-length-array (alloca was previouly used, but it cannot be
-	// safely used in loops).
+	// variable-length-array (alloca cannot be safely used in loops).
 	ast::ObjectDecl * newBuf = new ast::ObjectDecl( decl->location,
 		bufNamer.newName(),
@@ -2400,14 +2193,6 @@
 }
 
-void PolyGenericCalculator::beginGenericScope() {
-	GuardScope( *this );
-	// We expect the first function type see to be the type relating to this
-	// scope but any further type is probably some unrelated function pointer
-	// keep track of whrich is the first.
-	GuardValue( expect_func_type ) = true;
-}
-
 // --------------------------------------------------------------------------
-/// No common theme found.
+/// Removes unneeded or incorrect type information.
 /// * Replaces initialization of polymorphic values with alloca.
 /// * Replaces declaration of dtype/ftype with appropriate void expression.
@@ -2415,5 +2200,4 @@
 /// * Strips fields from generic structure declarations.
 struct Eraser final :
-		public BoxPass,
 		public ast::WithGuards {
 	void guardTypeVarMap( ast::Type const * type ) {
@@ -2430,4 +2214,6 @@
 	void previsit( ast::PointerType const * type );
 	void previsit( ast::FunctionType const * type );
+public:
+	TypeVarMap scopeTypeVars;
 };
 
Index: src/GenPoly/GenPoly.cc
===================================================================
--- src/GenPoly/GenPoly.cc	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ src/GenPoly/GenPoly.cc	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -273,5 +273,5 @@
 	if ( func->returns.empty() ) return nullptr;
 
-	TypeVarMap forallTypes = { ast::TypeData() };
+	TypeVarMap forallTypes;
 	makeTypeVarMap( func, forallTypes );
 	return isDynType( func->returns.front(), forallTypes );
@@ -801,5 +801,5 @@
 	const ast::FunctionType * function = getFunctionType( expr->func->result );
 	assertf( function, "ApplicationExpr has non-function type: %s", toString( expr->func->result ).c_str() );
-	TypeVarMap exprTyVars = { ast::TypeData() };
+	TypeVarMap exprTyVars;
 	makeTypeVarMap( function, exprTyVars );
 	return needsBoxing( param, arg, exprTyVars, subst );
Index: src/GenPoly/GenPoly.h
===================================================================
--- src/GenPoly/GenPoly.h	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ src/GenPoly/GenPoly.h	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -33,5 +33,7 @@
 
 	typedef ErasableScopedMap< std::string, TypeDecl::Data > TyVarMap;
-	using TypeVarMap = ErasableScopedMap< ast::TypeEnvKey, ast::TypeData >;
+	struct TypeVarMap : public ErasableScopedMap<ast::TypeEnvKey, ast::TypeData> {
+		TypeVarMap() : ErasableScopedMap( ast::TypeData() ) {}
+	};
 
 	/// Replaces a TypeInstType by its referrent in the environment, if applicable
Index: src/GenPoly/SpecializeNew.cpp
===================================================================
--- src/GenPoly/SpecializeNew.cpp	(revision 2bf46a5f6449a84ac68d5d0f9d73906608a06c99)
+++ src/GenPoly/SpecializeNew.cpp	(revision 1b41219dc836b5a59b65a2834352f9d6762a3243)
@@ -81,24 +81,20 @@
 }
 
-// The number of elements in a type if it is a flattened tuple.
-size_t flatTupleSize( const ast::Type * type ) {
-	if ( auto tuple = dynamic_cast<const ast::TupleType *>( type ) ) {
-		size_t sum = 0;
-		for ( auto t : *tuple ) {
-			sum += flatTupleSize( t );
-		}
-		return sum;
-	} else {
-		return 1;
-	}
+// The number of elements in a list, if all tuples had been flattened.
+size_t flatTypeListSize( const std::vector<ast::ptr<ast::Type>> & types ) {
+	size_t sum = 0;
+	for ( const ast::ptr<ast::Type> & type : types ) {
+		if ( const ast::TupleType * tuple = type.as<ast::TupleType>() ) {
+			sum += flatTypeListSize( tuple->types );
+		} else {
+			sum += 1;
+		}
+	}
+	return sum;
 }
 
 // Find the total number of components in a parameter list.
 size_t functionParameterSize( const ast::FunctionType * type ) {
-	size_t sum = 0;
-	for ( auto param : type->params ) {
-		sum += flatTupleSize( param );
-	}
-	return sum;
+	return flatTypeListSize( type->params );
 }
 
