many smaller updates
[phd-thesis.git] / dsl / dsl_techniques.tex
index 22b9977..ca4ce11 100644 (file)
@@ -5,46 +5,40 @@
 \begin{document}
 \chapter{\texorpdfstring{\Glsxtrshort{DSL}}{DSL} embedding techniques}%
 \label{chp:dsl_embedding_techniques}%
-An \gls{EDSL} is a language embedded in a host language created for a specific domain\todo{citation needed?}.
-Properties such as referential transparency, minimal syntax, powerful type systems and rich data types make \gls{FP} languages excellent candidates for hosting \glspl{EDSL}.
-
-There are two flavours of \gls{DSL} embedding: deep- and shallow embedding~\citep{boulton_experience_1992}.
-Shallow embedding---also called tagless embedding---models language constructs as functions in the host language.
-As a result, adding new language constructs---extra functions---is easy.
-However, the interpretation of the language is embedded in these functions, making it troublesome to add semantics since it requires updating all existing language constructs.
-
-In contrast to shallow embedding, deep embedding---also called tagged embedding---models terms in the language as data types.
-Interpretations are functions over these data types.
-
-Consequently, adding new semantics, i.e.\ novel functions, is straightforward.
-It can be stated that the language constructs are embedded in the functions that form a semantics.
-If one wants to add a language construct, all semantics functions must be revisited and revised to avoid ending up with partial functions.
-
-This juxtaposition has been known for many years~\citep{reynolds_user-defined_1978} and discussed by many others~\citep{krishnamurthi_synthesizing_1998} but most famously dubbed the \emph{expression problem} by Wadler~\citep{wadler_expression_1998}:
-
-\begin{quote}
-       The \emph{expression problem} is a new name for an old problem.
-       The goal is to define a data type by cases, where one can add new cases to the data type and new functions over the data type, without recompiling existing code, and while retaining static type safety (e.g., no casts).
-\end{quote}
-
-Terms in an \glspl{EDSL} can have multiple interpretations\footnote{Interpretations are also called backends or views}, i.e.\ a term in the \gls{DSL} is just an interface.
-Commonly used intepretations are printing, compiling, simulating, optimising, verifying, proving the program\etc.
-There are two main flavours of embedding \glspl{DSL}.
-Deep embedding---also called shallow--- models terms in the language as data types, interpretations are functions over these terms.
-Shallow embedding---also called tagless---models terms in the language as functions, interpretations are embedded in these functions.
-
-Most importantly, the two flavours differ on two axes: extensibility of language constructs and extensibility of interpretations.
-\todo{elaborate}
-
-\Cref{sec:deep_embedding} shows the basics of deep embedding.
-\Cref{sec:shallow_embedding} shows the basics of shallow embedding including tagless embedding.
-\Cref{sec:compare_embedding} compares the embedding technique.
-
-In the following sections the basics of both techniques are explained.
-A simple language with integers, booleans and some arithmetic operators is used as a running example.
+\begin{chapterabstract}
+       An \gls{EDSL} is a language embedded in a host language created for a specific domain\todo{citation needed?}.
+       Properties such as referential transparency, minimal syntax, powerful type systems and rich data types make \gls{FP} languages excellent candidates for hosting \glspl{EDSL}.
+       Terms in an \glspl{EDSL} can have multiple interpretations\footnote{Interpretations are also called backends or views}, i.e.\ a term in the \gls{DSL} is just an interface.
+       Commonly used intepretations are printing, compiling, simulating, optimising, verifying, proving the program\etc.
+       
+       There are two flavours of \gls{DSL} embedding: deep- and shallow embedding~\citep{boulton_experience_1992}.
+       Shallow or tagless embedding models language constructs as functions in the host language.
+       As a result, adding new language constructs---extra functions---is easy.
+       However, the interpretation of the language is embedded in these functions, making it troublesome to add semantics since it requires updating all existing language constructs.
+       
+       In contrast to shallow embedding, deep embedding or tagged models terms in the language as data types.
+       Interpretations are functions over these data types.
+       
+       Consequently, adding new semantics, i.e.\ novel functions, is straightforward.
+       It can be stated that the language constructs are embedded in the functions that form a semantics.
+       If one wants to add a language construct, all semantics functions must be revisited and revised to avoid ending up with partial functions.
+       
+       This juxtaposition has been known for many years~\citep{reynolds_user-defined_1978} and discussed by many others~\citep{krishnamurthi_synthesizing_1998} but most famously dubbed the \emph{expression problem} by \citet{wadler_expression_1998}:
+       
+       \begin{quote}
+               The \emph{expression problem} is a new name for an old problem.
+               The goal is to define a data type by cases, where one can add new cases to the data type and new functions over the data type, without recompiling existing code, and while retaining static type safety (e.g., no casts).
+       \end{quote}
+       
+%      Most importantly, the two flavours differ on two axes: extensibility of language constructs and extensibility of interpretations.
+%      \todo{elaborate}
+       
+       Using a simple language with integers, booleans and some arithmetic operators, \cref{sec:deep_embedding} shows some deep embedding variants and \cref{sec:shallow_embedding} shows the relevant shallow embedding variants.
+       \Cref{sec:compare_embedding} compares the embedding techniques.
+\end{chapterabstract}
 
 \section{Deep embedding}\label{sec:deep_embedding}
-In a deeply embedded \gls{DSL}, the language terms are represented as data type{(s)} in the host language.
+In a deeply embedded \gls{DSL}, the language terms are represented as data types in the host language.
 Therefore, interpretations of the terms are functions that operate on these data types.
 \Cref{lst:exdeep} shows an implementation for the example \gls{DSL}.
 
@@ -67,39 +61,37 @@ print (Eq l r)   = "(" ++ print l ++ "==" ++ print r ++ ")"
 \end{lstHaskell}
 
 Adding a construct---for example subtraction---reveals the Achilles' heel of deep embedding, namely that we need to revisit the original data type \emph{and} all the existing views.
-I.e.\ we need to add \haskellinline{| Sub Expr Expr} to the \haskellinline{Expr} data type.
+I.e.\ we need to add \haskellinline{\| Sub Expr Expr} to the \haskellinline{Expr} data type.
 Furthermore, we need to add \haskellinline{print (Sub l r) = ...} to the \haskellinline{print} view in order to not end up with a partial function.
-This limitation can be overcome by lifting the views to classes (See \cref{chp:classy_deep_embedding}).
+Using a novel variant of deep embedding, this limitation can be overcome by lifting the views to classes (see \cref{chp:classy_deep_embedding}).
 
-Implementing an evaluator for the language is possible without touching any original code, we just add a function operating on the \haskellinline{Expr} data type.
-To store variables, it has an extra environment argument.
+Implementing an extra view, an evaluator as shown in \cref{lst:deep_simple}, for the language is possible without touching any original code, we just add a function operating on the \haskellinline{Expr} data type.
 Here another downside of basic deep embedding arises immediately, the expressions are not typed, and therefore there has to be some type checking in the evaluation code.
 Luckily this problem can be overcome by switching from regular \glspl{ADT} to \glspl{GADT}, resulting in the following data type and evaluator.
 
-\begin{lstHaskell}[caption={An evaluator for the deeply embedded expression \gls{DSL}.}]
+\begin{lstHaskell}[label={lst:deep_simple},caption={An evaluator for the deeply embedded expression \gls{DSL}.}]
 eval :: Expr -> Value
 eval (Lit i)    = i
 eval (Plus l r) = case (eval l, eval r) of
        (Lit (I l), Lit (I r)) -> I (l+r))
-       (l, r)       -> error ("Can't add " ++ show l ++ " to " ++ show r)
+       (l, r) -> error ("Can't add " ++ show l ++ " to " ++ show r)
 eval (Eq l r) = case (eval l, eval r) of
        (Lit (I l), Lit (I r)) -> B (l==r)
        (Lit (B l), Lit (B r)) -> B (l==r)
-       (l, r)       -> error ("Can't compare " ++ show l ++ " to " ++ show r)
+       (l, r) -> error ("Can't compare " ++ show l ++ " to " ++ show r)
 \end{lstHaskell}
 
 \subsection{\texorpdfstring{\Glsxtrlongpl{GADT}}{Generalised algebraic data types}}
 Deep embedding has the advantage that it is easy to build and views are easy to add.
 On the downside, the expressions created with this language are not necessarily type-safe.
 In the given language it is possible to create an expression such as \haskellinline{LitI 4 `Plus` LitB True} that adds a boolean to an integer.
-Extending the \gls{ADT} is easy and convenient but extending the views accordingly is tedious since it has to be done individually for all views.
-
-The first downside of this type of \gls{EDSL} can be overcome by using \glspl{GADT}~\citep{cheney_first-class_2003}.
-\Cref{lst:exdeepgadt} shows the same language, but type-safe with a \gls{GADT}.
-\glspl{GADT} are not supported in the current version of \gls{CLEAN} and therefore the syntax is hypothetical (See \todo{insert link to appendix}).
-However, it has been shown that \glspl{GADT} can be simulated using bimaps or projection pairs~\citep[\citesection{2.2}]{cheney_lightweight_2002}.
-Unfortunately the lack of extendability remains a problem.
-If a language construct is added, no compile time guarantee can be given that all views support it.
+This downside of the \gls{EDSL} technique can be overcome by using \glspl{GADT} instead of \glspl{ADT}~\citep{cheney_first-class_2003}.
+Even if the host language does not support \glspl{GADT}, it has been shown that they can be simulated using bimaps or projection pairs~\citep[\citesection{2.2}]{cheney_lightweight_2002}.
+\Cref{lst:exdeepgadt} shows the same language, but made type-safe with a \gls{GADT}.
+The data types are annotated with a type variable representing the type of the expression.
+This restriction makes the evaluator's implementation much more concise.
+For the printer, the implementation can even remain the same.
+Only the type signature needs an update.
 
 \begin{lstHaskell}[label={lst:exdeepgadt},caption={A deeply embedded expression \gls{DSL} using \glspl{GADT}.}]
 data Expr a where
@@ -111,28 +103,26 @@ eval :: Expr a -> a
 eval (Lit i)    = i
 eval (Plus l r) = eval l + eval r
 eval (Eq l r)   = eval l == eval r
+
+print :: Expr a -> String
+...
 \end{lstHaskell}
 
 \section{Shallow embedding}\label{sec:shallow_embedding}
-In a shallowly \gls{EDSL} all language constructs are expressed as functions in the host language.
+In a shallowly embedded \gls{DSL} the language constructs are expressed as functions in the host language.
 An evaluator view for the example language then can be implemented as the code shown in \cref{lst:exshallow}.
-Note that the internals of the language could have been hidden using a reader monad.
 
 \begin{lstHaskell}[label={lst:exshallow}, caption={A minimal shallow \gls{EDSL}.}]
-type Env   = String -> Int
-type DSL a = Env -> a
-
-lit :: a -> DSL a
-lit x = \e->x
+data Eval a = Eval {runEval :: a}
 
-var :: String -> DSL Int
-var i = \e->retrEnv e i
+lit :: a -> Eval a
+lit x = Eval x
 
-plus :: DSL Int -> DSL Int -> DSL Int
-plus x y = \e->x e + y e
+plus :: Num a => Eval a -> Eval a -> Eval a
+plus x y = Eval (runEval x + runEval y)
 
-eq :: Eq a => DSL a -> DSL a -> DSL Bool
-eq x y = \e->x e == y e
+eq :: Eq a => Eval a -> Eval a -> Eval Bool
+eq x y = Eval (runEval x == runEval y)
 \end{lstHaskell}
 
 One of the advantages of shallowly embedding a language in a host language is its extendability.
@@ -140,28 +130,27 @@ It is very easy to add functionality because the compile time checks of the host
 For example, adding a new construct---such as subtraction---is done as follows:
 
 \begin{lstHaskell}[label={lst:exshallowsubst},caption={Adding subtraction to the shallow \gls{EDSL}.}]
-sub :: DSL Int -> DSL Int -> DSL Int
-sub x y = \e->x e - y e
+sub :: Num a => Eval a -> Eval a -> Eval a
+sub x y = Eval (runEval x - runEval y)
 \end{lstHaskell}
 
 Moreover, the language is type safe as it is directly typed in the host language, i.e.\ \haskellinline{lit True `plus` lit 4} is rejected.
 Another advantage is the intimate link with the host language, allowing for a lot more linguistic reuse such as the support of implicit sharing \citep{krishnamurthi_linguistic_2001}.
 
 The downside of this method is extending the language with views.
-It is nearly impossible to add views to a shallowly embedded language.
+Since the views are embedded, adding a view requires embedding combining the two views in some way.
 The only way of achieving this is by reimplementing all functions so that they run all backends at the same time or to create a single interpretation that produces a fold function \citep{gibbons_folding_2014}.
 
 \subsection{Tagless-final embedding}\label{ssec:tagless}
 By lifting the functions representing the \gls{DSL} terms to type classes, interpretations can be added.
-This technique is called tagless-final---or class-based shallow---embedding.
+This technique is called tagless-final---or class-based shallow---embedding~\citep{carette_finally_2009}.
 The interface for the \gls{DSL} looks as follows:
 
 \begin{lstHaskell}[label={lst:extagless},caption={A minimal tagless-final \gls{EDSL}.}]
 class DSL v where
-       lit :: a -> v a
-       var :: String -> v a
-       plus :: v Int -> v Int -> v Int
-       eq :: Eq a => v a -> v a -> v Bool
+       lit  :: Show a => a -> v a
+       plus :: Num a => v a -> v a -> v a
+       eq   :: Eq a => v a -> v a -> v Bool
 \end{lstHaskell}
 
 An interpretation of this view is a data type that implements the type class.
@@ -170,7 +159,6 @@ An interpretation of this view is a data type that implements the type class.
 data Print a = P {runPrint :: String}
 instance DSL Print where
        lit a = P (show a)
-       var i = P i
        plus x y = P ("(" ++ runPrint x ++ "+" ++ runPrint y ++ ")"
        eq x y = P ("(" ++ runPrint x ++ "==" ++ runPrint y ++ ")"
 \end{lstHaskell}
@@ -179,7 +167,7 @@ Adding a language construct---e.g.\ subtraction---is a easy as adding a type cla
 
 \begin{lstHaskell}[label={lst:extaglesssubt},caption={Adding subtraction to the shallow \gls{EDSL}.}]
 class Sub v where
-       sub :: v Int -> v Int -> v Int
+       sub :: Num a => v a -> v a -> v a
 
 instance Sub Print where
        sub x y = P ("(" ++ runPrint x ++ "-" ++ runPrint y ++ ")"
@@ -188,20 +176,22 @@ instance Sub Print where
 Adding an interpretation means adding a data type and providing instances for the language constructs.
 
 \begin{lstHaskell}[label={lst:extaglesseval},caption={An evaluator interpretation of the minimal tagless-final \gls{EDSL}.}]
-data Eval a = Eval {runEval :: Env -> a}
+data Eval a = Eval {runEval :: a}
 
 instance DSL v where
-       lit a = Eval (\_->a)
-       var i = Eval (\e->retrEnv e i)
-       plus x y = Eval (\e->runEval x e + runEval y e)
-       eq x y = Eval (\e->runEval x e == runEval y e)
+       lit a = Eval a
+       plus x y = Eval (runEval x + runEval y)
+       eq x y = Eval (runEval x == runEval y)
 
 instance Sub Eval where
-       sub x y = Eval (\e->runEval x e - runEval y e)
+       sub x y = Eval (runEval x - runEval y)
 \end{lstHaskell}
 
+\section{Other embedding techniques}\label{sec:other}
 \section{Comparison}\label{sec:compare_embedding}
-Both flavours have their strengths and weaknesses and both flavours can be improved in order to mitigate (some of the) downsides.
+Both flavours have their strengths and weaknesses.
+As we have seen with \glspl{GADT} for deep embedding and tagless-final for shallow embedding, both flavours can be improved in some way in order to mitigate (some of the) downsides.
+Besides deep and shallow embedding, there are some more advanced variants that try to mitigate some of the problems.
 
 \begin{table}[ht]
        \begin{threeparttable}[b]
@@ -209,7 +199,7 @@ Both flavours have their strengths and weaknesses and both flavours can be impro
                \label{tbl:dsl_comparison}
                \begin{tabular}{lllllll}
                        \toprule
-                                                                       & Shallow & Deep  & Hybrid          & Poly           & Comp. & Classy\\
+                                                                       & Shallow & Deep  & Hybrid          & Poly           & Comp.          & Classy\\
                        \midrule
                        Transcoding free        & yes     & yes   & no              & yes            & yes            & yes\\
                        Linguistic reuse        & yes     & no    & partly\tnote{1} & yes            & yes            & no?\\