# Changeset 90cfc16 for doc

Ignore:
Timestamp:
Dec 11, 2018, 2:42:27 PM (3 years ago)
Branches:
aaron-thesis, arm-eh, cleanup-dtors, deferred_resn, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, no_list, persistent-indexer
Children:
5307c33, 85acec94
Parents:
1f690b3 (diff), 29207bf (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Location:
doc
Files:
5 edited

Unmodified
Removed
• ## doc/bibliography/pl.bib

 r1f690b3 %  toplas: ACM Trans. on Prog. Lang. & Sys. %  tcs: Theoretical Computer Science @string{ieeepds="IEEE Transactions on Parallel and Distributed Systems"} % @string{ieeepds="IEEE Trans. Parallel Distrib. Syst."} @string{ieeese="IEEE Transactions on Software Engineering"} % @string{ieeese="IEEE Trans. Softw. Eng."} @string{spe="Software---\-Practice and Experience"} % @string{spe="Softw. Pract. Exp."} @string{ccpe="Concurrency and Computation: Practice and Experience"} % @string{ccpe="Concurrency Comput: Pract Experience"} @string{sigplan="SIGPLAN Notices"} % @string{sigplan="SIGPLAN Not."} @string{joop="Journal of Object-Oriented Programming"} % @string{joop="J. of Object-Oriented Program."} string{ieeepds="IEEE Transactions on Parallel and Distributed Systems"} @string{ieeepds="IEEE Trans. Parallel Distrib. Syst."} string{ieeese="IEEE Transactions on Software Engineering"} @string{ieeese="IEEE Trans. Softw. Eng."} string{spe="Software---\-Practice and Experience"} @string{spe="Softw. Pract. Exper."} string{ccpe="Concurrency and Computation: Practice and Experience"} @string{ccpe="Concurrency Comput.: Pract. Exper."} string{sigplan="SIGPLAN Notices"} @string{sigplan="SIGPLAN Not."} string{joop="Journal of Object-Oriented Programming"} @string{joop="J. of Object-Oriented Program."} @string{popl="Conference Record of the ACM Symposium on Principles of Programming Languages"} @string{osr="Operating Systems Review"} @string{pldi="Programming Language Design and Implementation"} @string{toplas="Transactions on Programming Languages and Systems"} @string{mathann="Mathematische Annalen"} % @string{mathann="Math. Ann."} string{mathann="Mathematische Annalen"} @string{mathann="Math. Ann."} % A } @inproceedings {Qin18, author      = {Henry Qin and Qian Li and Jacqueline Speiser and Peter Kraft and John Ousterhout}, title       = {Arachne: Core-Aware Thread Management}, booktitle   = {13th {USENIX} Symp. on Oper. Sys. Design and Impl. ({OSDI} 18)}, year        = {2018}, address     = {Carlsbad, CA}, pages       = {145-160}, publisher   = {{USENIX} Association}, note        = {\href{https://www.usenix.org/conference/osdi18/presentation/qin}{https://\-www.usenix.org/\-conference/\-osdi18/\-presentation/\-qin}}, } @article{Kessels82, keywords    = {concurrency, critical section}, author      = {Joung, Yuh-Jzer}, title       = {Asynchronous group mutual exclusion}, journal     = {Distributed Computing}, journal     = {Dist. Comput.}, optjournal  = {Distributed Computing}, year        = {2000}, month       = {Nov}, time computable inheritance hierarchy. }, comment = { comment     = { Classes are predicates; if object {\tt o} is in class {\tt C}, then {\tt C} is true of {\tt o}.  Classes are combined with {\tt :AND}, @article{Moss18, keywords    = {type systems, tuples, Cforall}, keywords    = {type systems, polymorphism, tuples, Cforall}, contributer = {pabuhr@plg}, author      = {Aaron Moss and Robert Schluntz and Peter A. Buhr}, title       = {\textsf{C}$\mathbf{\forall}$ : Adding Modern Programming Language Features to C}, journal     = spe, volume      = 48, number      = 12, month       = dec, year        = 2018, month       = aug, journal     = spe, pages       = {2111-2146}, note        = {\href{http://dx.doi.org/10.1002/spe.2624}{http://\-dx.doi.org/\-10.1002/\-spe.2624}}, } journal     = {Dr. Dobb's Journal of Software Tools}, year        = 1989, month       = feb, volume = 14, number = 2, pages = {45-51}, month       = feb, volume      = 14, number      = 2, pages       = {45-51}, comment     = { A light-weight multitasking kernel for MS-DOS.  A task\_control } @techreport{uC++, @manual{uC++, keywords    = {C++, concurrency, light-weight process, shared memory}, contributer = {pabuhr@plg}, key         = {uC++}, author      = {Peter A. Buhr}, title       = {$\mu${C}{\kern-.1em\hbox{\large\texttt{+\kern-.25em+}}} Annotated Reference Manual, Version 7.0.0}, institution = {School of Computer Science, University of Waterloo}, address     = {Waterloo, Ontario, Canada, N2L 3G1}, month       = dec, year        = 2017, organization= {University of Waterloo}, month       = sep, year        = 2018, note        = {\href{https://plg.uwaterloo.ca/~usystem/pub/uSystem/uC++.pdf}{https://\-plg.uwaterloo.ca/\-$\sim$usystem/\-pub/\-uSystem/uC++.pdf}}, } author      = {Sun, Xianda}, title       = {Concurrent High-performance Persistent Hash Table In {J}ava}, school      = {School of Computer Science, University of Waterloo}, school      = {School of Computer Sc., University of Waterloo}, year        = 2015, optaddress  = {Waterloo, Ontario, Canada, N2L 3G1}, note        = {Svensk Standard SS 63 61 14}, year        = 1987, abstract    = { Standard for the programming language SIMULA.  Written in English. } abstract    = {Standard for the programming language SIMULA. Written in English.} } @article{Galil91, keywords    = {union-find}, contributer = {a3moss@uwaterloo.ca}, title       = {Data structures and algorithms for disjoint set union problems}, author      = {Galil, Zvi and Italiano, Giuseppe F}, journal     = {ACM Computing Surveys (CSUR)}, volume      = 23, number      = 3, pages       = {319--344}, year        = 1991, publisher   = {ACM}, } year        = {1998}, pages       = {393-407}, } @book{Aho74, keywords    = {algorithms, textbook, union-find}, contributer = {a3moss@uwaterloo.ca}, title       = {The Design and Analysis of Computer Algorithms}, author      = {Aho, Alfred V and Hopcroft, John E and Ullman, Jeffrey D}, year        = {1974}, publisher   = {Addison-Wesley}, address     = {Reading, MA, USA} } } @inproceedings{Patwary10, keywords    = {union-find}, contributer = {a3moss@uwaterloo.ca}, author      = {Patwary, Md. Mostofa Ali and Blair, Jean and Manne, Fredrik}, editor      = {Festa, Paola}, title       = {Experiments on Union-Find Algorithms for the Disjoint-Set Data Structure}, booktitle   = {Experimental Algorithms}, year        = 2010, publisher   = {Springer Berlin Heidelberg}, address     = {Berlin, Heidelberg}, pages       = {411--423}, isbn        = {978-3-642-13193-6} } % F keywords    = {Go programming language}, contributer = {pabuhr@plg}, author      = {Robert Griesemer and Rob Pike and Ken Thompson}, title       = {{Go} Programming Language}, author      = {Robert Griesemer and Rob Pike and Ken Thompson}, organization= {Google}, year        = 2009, month       = sep, publisher   = {John Wiley \& Sons}, note        = {\href{https://doi-org.proxy.lib.uwaterloo.ca/10.1002/cpe.4475}{https://\-doi-org.proxy.lib.uwaterloo.ca/\-10.1002/\-cpe.4475}}, note        = {\href{https://doi.org/10.1002/cpe.4475}{https://\-doi.org/\-10.1002/\-cpe.4475}}, } publisher   = {ACM Press}, address     = {New York, NY, USA}, } @article{Galler64, keywords    = {union-find, original}, contributer = {a3moss@uwaterloo.ca}, title       = {An improved equivalence algorithm}, author      = {Galler, Bernard A and Fisher, Michael J}, journal     = {Communications of the ACM}, volume      = {7}, number      = {5}, pages       = {301--303}, year        = {1964}, publisher   = {ACM} } author      = {Peter A. Buhr and Martin Karsten and Jun Shih}, title       = {{\small\textsf{KDB}}: A Multi-threaded Debugger for Multi-threaded Applications}, booktitle   = {Proceedings of SPDT'96: SIGMETRICS Symposium on Parallel and Distributed Tools}, booktitle   = {Proc. of SPDT'96: SIGMETRICS Symp. on Parallel and Distributed Tools}, publisher   = {ACM Press}, address     = {Philadelphia, Pennsylvania, U.S.A.}, } @inproceedings{Conchon07, keywords    = {persistent array, union-find}, contributer = {a3moss@uwaterloo.ca}, title       = {A persistent union-find data structure}, author      = {Conchon, Sylvain and Filli{\^a}tre, Jean-Christophe}, booktitle   = {Proceedings of the 2007 workshop on Workshop on ML}, pages       = {37--46}, year        = {2007}, organization= {ACM} } @article{poly, keywords    = {Poly, Standard ML, Russell, persistence}, author      = {Peter A. Buhr and Robert Denda}, title       = {{$\mu$Profiler} : Profiling User-Level Threads in a Shared-Memory Programming Environment}, booktitle   = {Proceedings of the Second International Symposium on Computing in Object-Oriented Parallel Environments (ISCOPE'98)}, booktitle   = {Proc. of 2nd Inter. Symp. on Computing in Object-Oriented Parallel Environments}, series      = {Lecture Notes in Computer Science}, publisher   = {Springer-Verlag}, issn        = {0164-0925}, pages       = {429-475}, url         = {http://doi.acm.org.proxy.lib.uwaterloo.ca/10.1145/1133651.1133653}, url         = {http://doi.acm.org/10.1145/1133651.1133653}, doi         = {10.1145/1133651.1133653}, acmid       = {1133653}, contributer = {pabuhr@plg}, key         = {Rust}, title       = {The {R}ust Programming Language}, address     = {The Rust Project Developers}, title       = {{R}ust Programming Language}, optaddress  = {Rust Project Developers}, year        = 2015, note        = {\href{https://doc.rust-lang.org/reference.html}{https://\-doc.rust-lang\-.org/\-reference.html}}, publisher   = {Springer}, note        = {Lecture Notes in Computer Science v. 173}, } @article{Baker78, keywords    = {Algol display, FUNARG's, Lisp 1.5, deep binding, environment trees, multiprogramming, shallow binding}, contributer = {a3moss@uwaterloo.ca}, author      = {Baker,Jr., Henry G.}, title       = {Shallow Binding in Lisp 1.5}, journal     = {Commun. ACM}, issue_date  = {July 1978}, volume      = 21, number      = 7, month       = jul, year        = 1978, issn        = {0001-0782}, pages       = {565--569}, numpages    = {5}, url         = {http://doi.acm.org/10.1145/359545.359566}, doi         = {10.1145/359545.359566}, acmid       = {359566}, publisher   = {ACM}, address     = {New York, NY, USA} } @article{Baker91, keywords    = {shallow binding, functional arrays}, contributer = {a3moss@uwaterloo.ca}, author      = {Baker, Henry G.}, title       = {Shallow Binding Makes Functional Arrays Fast}, journal     = {SIGPLAN Not.}, issue_date  = {Aug. 1991}, volume      = 26, number      = 8, month       = aug, year        = 1991, issn        = {0362-1340}, pages       = {145--147}, numpages    = {3}, url         = {http://doi.acm.org/10.1145/122598.122614}, doi         = {10.1145/122598.122614}, acmid       = {122614}, publisher   = {ACM}, address     = {New York, NY, USA}, } } @article{Tarjan84, keywords    = {union-find}, contributer = {a3moss@uwaterloo.ca}, author      = {Tarjan, Robert E. and van Leeuwen, Jan}, title       = {Worst-case Analysis of Set Union Algorithms}, journal     = {J. ACM}, issue_date  = {April 1984}, volume      = 31, number      = 2, month       = mar, year        = 1984, issn        = {0004-5411}, pages       = {245--281}, numpages    = {37}, url         = {http://doi.acm.org/10.1145/62.2160}, doi         = {10.1145/62.2160}, acmid       = {2160}, publisher   = {ACM}, address     = {New York, NY, USA}, } % X
• ## doc/theses/aaron_moss_PhD/phd/thesis.tex

 r1f690b3 % \usepackage[pdftex]{graphicx} % For including graphics N.B. pdftex graphics driver \usepackage{graphicx} \usepackage{amsthm} % for theorem environment \newtheorem{theorem}{Theorem} \usepackage{footmisc} % for double refs to the same footnote
• ## doc/theses/aaron_moss_PhD/phd/type-environment.tex

 r1f690b3 As discussed in Chapter~\ref{resolution-chap}, being able to efficiently determine which type variables are bound to which concrete types or whether two type environments are compatible is a core requirement of the resolution algorithm. Furthermore, expression resolution involves a search through many related possible solutions, so being able to re-use shared subsets of type environment data and to switch between environments quickly is desirable for performance. In this chapter I discuss and empirically compare a number of type environment data structure variants, including some novel variations on the union-find\cit{} data structure introduced in this thesis. \section{Definitions} In this chapter I discuss and empirically compare a number of type environment data structure variants, including some novel variations on the union-find\cite{Galler64} data structure introduced in this thesis. \section{Definitions} \label{env-defn-sec} For purposes of this chapter, a \emph{type environment} $T$ is a set of \emph{type classes} $\myset{T_1, T_2, \cdots, T_{|T|}}$. $add(T_i, v_{i,j})$ &                                                           & Add variable to class                 \\ $bind(T_i, b_i)$ &                                                                      & Set or update class bound             \\ $remove(T, T_i)$ &                                                                      & Remove class from environment \\ $unify(T, T_i, T_j)$ & $\rightarrow \top | \bot$        & Combine two type classes              \\ $split(T, T_i)$ & $\rightarrow T'$                                      & Revert the last $unify$ operation on $T_i$            \\ $combine(T, T')$ & $\rightarrow \top | \bot$            & Merge two environments                \\ $save(T)$ & $\rightarrow H$                                                     & Get handle for current state  \\ The $add(T_i, v_{i,j})$ operation adds a new type variable $v_{i,j}$ to class $T_i$; again, $v_{i,j}$ cannot exist elsewhere in $T$. $bind(T_i, b_i)$ mutates the bound for a type class, setting or updating the current bound. The final basic mutation operation is $remove(T, T_i)$, which removes a class $T_i$ and all its type variables from an environment $T$. The $unify$ operation is the fundamental non-trivial operation a type environment data structure must support. $unify(T, T_i, T_j)$ merges a type class $T_j$ into another $T_i$, producing a failure result and leaving $T$ in an invalid state if this merge fails. It is always possible to unify the type variables of both classes by simply taking the union of both sets; given the disjointness property, no checks for set containment are required, and the variable sets can simply be concatenated if supported by the underlying data structure. $unify$ depends on an internal $unify_bound$ operation which may fail. In \CFACC{}, $unify_bound(b_i, b_j) \rightarrow b'_i|\bot$ checks that the type classes contain the same sort of variable, takes the tighter of the two conversion permissions, and checks if the bound types can be unified. If the bound types cannot be unified (\eg{} !struct A! with !int*!), then $unify_bound$ fails, while other combinations of bound types may result in recursive calls. For instance, unifying !R*! with !S*! for type variables !R! and !S! will result in a call to $unify(T, find($!R!$), find($!S!$))$, while unifying !R*! with !int*! will result in a call to $unify_bound$ on !int! and the bound type of the class containing !R!. $unify$ depends on an internal $unifyBound$ operation which may fail. In \CFACC{}, $unifyBound(b_i, b_j) \rightarrow b'_i|\bot$ checks that the type classes contain the same sort of variable, takes the tighter of the two conversion permissions, and checks if the bound types can be unified. If the bound types cannot be unified (\eg{} !struct A! with !int*!), then $unifyBound$ fails, while other combinations of bound types may result in recursive calls. For instance, unifying !R*! with !S*! for type variables !R! and !S! will result in a call to $unify(T, find($!R!$), find($!S!$))$, while unifying !R*! with !int*! will result in a call to $unifyBound$ on !int! and the bound type of the class containing !R!. As such, a call to $unify(T, T_i, T_j)$ may touch every type class in $T$, not just $T_i$ and $T_j$, collapsing the entirety of $T$ into a single type class in extreme cases. For more information on \CFA{} unification, see \cite{Bilson03}. The inverse of $unify$ is $split(T, T_i)$, which produces a new environment $T'$ which is the same as $T$ except that $T_i$ has been replaced by two classes corresponding to the arguments to the previous call to $unify$ on $T_i$. If there has been no call to $unify$ on $T_i$ (\ie{} $T_i$ is a single-element class) $T_i$ is absent in $T'$. Given the nature of the expression resolution problem as backtracking search, caching and concurrency are both useful tools to decrease runtime. The invalid state of $T$ on failure is not important, given that a combination failure will result in the resolution algorithm backtracking to a different environment. $combine$ proceeds by calls to $insert$, $add$, and $unify$ as needed, and can be roughly thought of as calling $unify$ on every pair of classes in $T$ that have variables $v'_{i,j}$ and $v'_{i,k}$ in the same class $T'_i$ in $T'$. Like for $unify$, $combine$ can always find a mutually-consistent division of type variables into classes (in the extreme case, all type variables from $T$ and $T'$ in a single type class), but may fail due to inconsistent bounds on merged type classes. Like $unify$, $combine$ can always find a mutually-consistent partition of type variables into classes (in the extreme case, all type variables from $T$ and $T'$ in a single type class), but may fail due to inconsistent bounds on merged type classes. Finally, the backtracking access patterns of the compiler can be exploited to reduce memory usage or runtime through use of an appropriately designed data structure. The set of mutations to a type environment across the execution of the resolution algorithm produce an implicit tree of related environments, and the backtracking search typically focuses only on one leaf of the tree at once, or at most a small number of closely-related nodes as arguments to $combine$. As such, the ability to save and restore particular type environment states is useful, and supported by the $save(T) \rightarrow H$ and $backtrack(T, H)$ operations, which produce a handle for the current environment state and mutate an environment back to a previous state, respectively. These operations can be naively implemented by a deep copy of $T$ into $H$ and vice versa, but have more efficient implementations in persistency-aware data structures. These operations can be naively implemented by a deep copy of $T$ into $H$ and vice versa, but have more efficient implementations in persistency-aware data structures. \section{Approaches} \subsection{Na\"{\i}ve} The type environment data structure used in Bilson's\cite{Bilson03} original implementation of \CFACC{} is a straightforward translation of the definitions in Section~\ref{env-defn-sec} to \CC{} code; a !TypeEnvironment! contains a list of !EqvClass! type equivalence classes, each of which contains the type bound information and a tree-based sorted set of type variables. This approach has the benefit of being easy to understand and not imposing life-cycle or inheritance constraints on its use, but, as can be seen in Table~\ref{env-bounds-table}, does not support many of the desired operations with any particular efficiency. Some variations on this structure may improve performance somewhat; for instance, replacing the !EqvClass! variable storage with a hash-based set would reduce search and update times from $O(\log n)$ to amortized $O(1)$, while adding an index for the type variables in the entire environment would remove the need to check each type class individually to maintain the disjointness property. These improvements do not change the fundamental issues with this data structure, however. \subsection{Incremental Inheritance} One more invasive modification to this data structure which I investigated is to support swifter combinations of closely-related environments in the backtracking tree by storing a reference to a \emph{parent} environment within each environment, and having that environment only store type classes which have been modified with respect to the parent. This approach provides constant-time copying of environments, as a new environment simply consists of an empty list of type classes and a reference to its (logically identical) parent; since many type environments are no different than their parent, this speeds backtracking in this common case. Since all mutations made to a child environment are by definition compatible with the parent environment, two descendants of a common ancestor environment can be combined by iteratively combining the changes made in one environment then that environment's parent until the common ancestor is reached, again re-using storage and reducing computation in many cases. For this environment I also employed a lazily-generated index of type variables to their containing class, which could be in either the current environment or an ancestor. Any mutation of a type class in an ancestor environment would cause that class to be copied into the current environment before mutation, as well as added to the index, ensuring that all local changes to the type environment are listed in its index. However, not adding type variables to the index until lookup or mutation preserves the constant-time environment copy operation in the common case in which the copy is not mutated from its parent during its life-cycle. This approach imposes some performance penalty on $combine$ if related environments are not properly linked together, as the entire environment needs to be combined rather than just the diff, but is correct as long as the null parent'' base case is properly handled. The life-cycle issues are somewhat more complex, as many environments may descend from a common parent, and all of these need their parent to stay alive for purposes of lookup. These issues can be solved by flattening'' parent nodes into their children before the parents leave scope, but given the tree structure of the inheritance graph it is more straightforward to store the parent nodes in reference-counted or otherwise automatically garbage-collected heap storage. \subsection{Union-Find} \label{env-union-find-approach} Given the nature of the classes of type variables as disjoint sets, another natural approach to implementing a type environment is the union-find disjoint set data structure\cite{Galler64}. Union-find efficiently implements two operations over a partition of a collection of elements into disjoint sets; $find(x)$ locates the \emph{representative} of $x$, the element which canonically names its set, while $union(r, s)$ merges two sets represented by $r$ and $s$, respectively. The union-find data structure is based on providing each element with a reference to its parent element, such that the root of a tree of elements is the representative of the set of elements contained in the tree. $find$ is then implemented by a search up to the parent, generally combined with a \emph{path compression} step that links nodes more directly to their ancestors to speed up subsequent searches. $union$ involves making the representative of one set a child of the representative of the other, generally employing a rank- or size-based heuristic to ensure that the tree remains somewhat balanced. If both path compression and a balancing heuristic are employed, both $union$ and $find$ run in amortized $O(\alpha(n))$ worst-case time; this bound by the inverse Ackermann function is a small constant for all practical values of $n$. The union-find $find$ and $union$ operations have obvious applicability to the $find$ and $unify$ type environment operations in Table~\ref{env-op-table}, but the union-find data structure must be augmented to fully implement the type environment operations. In particular, the type class bound cannot be easily included in the union-find data structure, as the requirement to make it the class representative breaks the balancing properties of $union$, and requires too-close integration of the type environment $unifyBound$ internal operation. This issue can be solved by including a side map from class representatives to the type class bound. If placeholder values are inserted in this map for type classes without bounds than this also has the useful property that the key set of the map provides an easily obtainable list of all the class representatives, a list which cannot be derived from the union-find data structure without a linear search for class representatives through all elements. \subsection{Union-Find with Classes} \label{env-union-find-classes-approach} Another type environment operation not supported directly by the union-find data structure is $report$, which lists the type variables in a given class, and similarly $split$, which reverts a $unify$ operation. Since the union-find data structure stores only links from children to parents and not vice-versa, there is no way to reconstruct a class from one of its elements without a linear search over the entire data structure, with $find$ called on each element to check its membership in the class. The situation is even worse for the $split$ operation, which would require extra information to maintain the order that each child was added to its parent node. Unfortunately, the literature\cite{Tarjan84,Galil91,Patwary10} on union-find does not present a way to keep references to children without breaking the asymptotic time bounds of the algorithm; I have discovered a method to do so which, despite its simplicity, seems to be novel. \TODO{port figure from slideshow} The core idea of this union-find with classes'' data structure and algorithm is to keep the members of each class stored in a circularly-linked list. Aho, Hopcroft, and Ullman also include a circularly-linked list in their 1974 textbook~\cite{Aho74}. However, the algorithm presented by Aho~\etal{} has an entirely flat class hierarchy, where all elements are direct children of the representative, giving constant-time $find$ at the cost of linear-time $union$ operations. In my version, the list data structure does not affect the layout of the union-find tree, maintaining the same asymptotic bounds as union-find. In more detail, each element is given a !next! pointer to another element in the same class; this !next! pointer initially points to the element itself. When two classes are unified, the !next! pointers of the representatives of those classes are swapped, splicing the two circularly-linked lists together. Importantly, though this approach requires an extra pointer per element, it does maintain the linear space bound of union-find, and because it only requires updating the two root nodes in $union$ it does not asymptotically increase runtime either. The basic approach is compatible with all path-compression techniques, and allows the members of any class to be retrieved in time linear in the size of the class simply by following the !next! pointers from any element. If the path-compression optimization is abandoned, union-find with classes also encodes a reversible history of all the $union$ operations applied to a given class. Theorem~\ref{env-reverse-thm} demonstrates that the !next! pointer of the representative of a class always points to a leaf from the last-added subtree. This property is sufficient to reverse the most-recent $union$ operation by finding the ancestor of that leaf that is an immediate child of the representative, breaking its parent link, and swapping the !next! pointers back\footnote{Union-by-size may be a more appropriate approach than union-by-rank in this instance, as adding two known sizes is a reversible operation, but the rank increment operation cannot be reliably reversed.}. Once the $union$ operation has been reversed, Theorem~\ref{env-reverse-thm} still holds for the reduced class, and the process can be repeated recursively until the entire set is split into its component elements. \begin{theorem} \label{env-reverse-thm} The !next! pointer of a class representative in the union-find with classes algorithm without path compression points to a leaf from the most-recently-added subtree. \end{theorem} \begin{proof} By induction on the height of the tree. \\ \emph{Base case:} A height 1 tree by definition includes only a single item. In such a case, the representative's !next! pointer points to itself by construction, and the representative is the most-recently-added (and only) leaf in the tree. \\ \emph{Inductive case:} By construction, a tree $T$ of height greater than 1 has children of the root (representative) node that were representative nodes of classes merged by $union$. By definition, the most-recently-added subtree $T'$ has a smaller height than $T$, thus by the inductive hypothesis before the most-recent $union$ operation the !next! pointer of the root of $T'$ pointed to one of the leaf nodes of $T'$; by construction the !next! pointer of the root of $T$ points to this leaf after the $union$ operation. \end{proof} On its own, union-find, like the na\"{\i}ve approach, has no special constraints on life-cycle or inheritance, but it can be used as a building block in more sophisticated type environment data structures. \subsection{Persistent Union-Find} Given the backtracking nature of the resolution algorithm discussed in Section~\ref{env-defn-sec}, the abilities to quickly switch between related versions of a type environment and to de-duplicate shared data between environments are both assets to performance. Conchon and Filli\^{a}tre~\cite{Conchon07} present a persistent union-find data structure based on the persistent array of Baker~\cite{Baker78,Baker91}. \TODO{port figure from slideshow} In Baker's persistent array, an array reference contains either a pointer to the array or a pointer to an \emph{edit node}; these edit nodes contain an array index, the value in that index, and another array reference pointing either to the array or a different edit node. In this manner, a tree of edits is formed, rooted at the actual array. Read from the actual array at the root can be performed in constant time, as with a non-persistent array. The persistent array can be mutated in constant time by directly modifying the underlying array, then replacing its array reference with an edit node containing the mutated index, the previous value at that index, and a reference to the mutated array. If the current array reference is not the root, mutation consists simply of constructing a new edit node encoding the change and referring to the current array reference. The mutation algorithm at the root is in some sense a special case of the key operation on persistent arrays, $reroot$. A rerooting operation takes any array reference and makes it the root node of the array. This is accomplished by tracing the path from some edit node to the root node of the array (always the underlying array), recursively applying the edits to the underlying array and replacing each edit node's successor with the inverse edit. In this way, any previous state of the persistent array can be restored in time proportional to the number of edits to the current state of the array. While $reroot$ does maintain the same value mapping in every version of the persistent array, the internal mutations it performs means that it is not thread-safe, and must be used behind a lock in a concurrent context. Also, the root node with the actual array may in principle be anywhere in the tree, and does not provide information to report its leaf nodes, so some form of automatic garbage collection is generally required for the data structure. Since the graph of edit nodes is tree-structured, reference counting approaches suffice for garbage collection; Conchon and Filli\^{a}tre~\cite{Conchon07} also observe that if the only $reroot$ operations are for backtracking then the tail of inverse edit nodes may be elided, suggesting the possibility of stack-based memory management. While Conchon and Filli\^{a}tre~\cite{Conchon07} implement their persistent union-find data structure over a universe of integer elements in the fixed range $[1,N]$, the type environment problem needs more flexibility. In particular, an arbitrary number of type variables must be added to the environment. As such, a persistent hash table is a more suitable structure than a persistent array, providing the same expected asymptotic time bounds while allowing a dynamic number of elements. Besides replacing the underlying array with a hash table, the other major change in this approach is to replace the two types of array references, !Array! and !Edit!, with four node types, !Table!,  !Edit!, !Add!, and !Remove!, where !Add! adds a new key-value pair, !Remove! removes a key, and !Edit! mutates an existing key-value pair. In this variant of \CFACC{}, this persistent hash table is used as the side map discussed in Section~\ref{env-union-find-approach} for class bounds. The actual union-find data structure is slightly modified from this approach, with a !Base! node containing the root union-find data structure, !Add! nodes adding new elements, !AddTo! nodes defining the union of two type classes, and !Remove! and !RemoveFrom! nodes as inverses of the previous two elements, for purposes of maintaining the edit list. Making !AddTo! and !RemoveFrom! single nodes shortens the edit path for improved performance, while also providing semantic information missing from the raw array updates in Conchon and Filli\^{a}tre's data structure. The single-node approach, does, however, break under most path-compression algorithms; !RemoveFrom! can be applied to the underlying data structure using the leaf of last union'' approach discussed in in Section~\ref{env-union-find-classes-approach}; this was judged an acceptable trade-off for the added semantic information and shortened paths. Maintaining explicit information on $union$ operations in the persistent union-find edit tree in the form of !AddTo! and !RemoveFrom! nodes exposes a new option for combining type environments. If the type environments are part of the same edit tree, one environment $T'$ can be combined with another $T$ by only testing the edits on the path from $T'$ to $T$ in both the persistent union-find data structure describing the classes and the persistent hash table containing the class bounds. This is generally more efficient than testing the compatibility of all type classes in $T'$, as only those that are actually different than those in $T$ must be considered. The procedure for $combine(T, T')$ based on edit paths is as follows: The shared edit trees for classes and bindings are rerooted at $T$, and the path from $T'$ to $T$ is followed to create a list of actual edits. By tracking the state of each element, redundant changes such as an !Edit! followed by an !Edit! can be reduced to their form in $T'$ by dropping the later (more like $T$) !Edit! for the same key; !Add! and !Remove! cancel similarly. This procedure is repeated for both the class edit tree and the binding edit tree. When the list of net changes to the environment has been produced, the additive changes are applied to $T$. For example, if a type class exists in $T'$ but not $T$, the corresponding !Add! edit will be applied to $T$, but in the reverse situation the !Remove! edit will not be applied to $T$, as the intention is to produce a new environment representing the union of the two sets of type classes; similarly, !AddTo! edits are applied to unify type-classes in $T$ that are united in $T'$, but !RemoveFrom! edits that split type classes are not. The new environment, $T''$ can always be constructed with a consistent partitioning of type variables; in the extreme case, all variables from both $T$ and $T'$ will be united in a single type class in $T''$. Where $combine$ can fail is in unifying the bound types; if any class in $T'$ has a class bound which does not unify with the merged class in $T''$ than $combine$ fails. \section{Analysis} In this section I present asymptotic analyses of the various approaches to a type environment data structure discussed in the previous section. \begin{table} \caption[Type environment operation bounds]{Worst-case analysis of type environment operations. $n$ is the number of type classes, $m$ the maximum size of a type class, and $p$ the edit distance between two environments or a single environment and the empty environment; $u(n)$ captures the recursive cost of class unification.} \label{env-bounds-table} \centering \begin{tabular}{rllll} \hline & \textbf{Na\"{\i}ve}   & \textbf{Incremental}  & \textbf{Union-Find}           & \textbf{U-F with Classes}             \\ \hline $find$          & $O(n)$                                & $O(p)$                                & $O(\alpha(m))$                        & $O(\log m)$                                   \\ $report$        & $O(m)$                                & $O(m)$                                & $O(n \log m)$                         & $O(m)$                                                \\ $bound$         & $O(1)$                                & $O(1)$                                & $O(1)$                                        & $O(1)$                                                \\ $insert$        & $O(1)$                                & $O(1)$                                & $O(1)$                                        & $O(1)$                                                \\ $add$           & $O(1)$                                & $O(1)$                                & $O(1)$                                        & $O(1)$                                                \\ $bind$          & $O(1)$                                & $O(1)$                                & $O(1)$                                        & $O(1)$                                                \\ $unify$         & $O(m + u(n))$                 & $O(m + u(n))$                 & $O(\log m + u(n))$            & $O(\log m + u(n))$                    \\ $split$         & ---                                   & ---                                   & ---                                           & $O(\log m)$                                   \\ $combine$       & $O(nm \cdot u(n))$    & $O(pm \cdot u(n))$    & $O(n \log m \cdot u(n))$      & $O(p \log m \cdot u(n))$              \\ $save$          & $O(nm)$                               & $O(1)$                                & $O(nm)$                                       & $O(1)$                                                \\ $backtrack$     & $O(nm)$                               & $O(pm)$                               & $O(nm)$                                       & $O(p)$                                                \\ \hline \end{tabular} \end{table} % Future work: design multi-threaded version of C&F persistent map --- core idea is some sort of thread-boundary edit node
• ## doc/user/Makefile

 r1f690b3 ## Define the default recipes. ${Build}:${Build} : mkdir -p \${Build}