\documentclass[../thesis.tex]{subfiles}

\begin{document}
\ifSubfilesClassLoaded{
	\pagenumbering{arabic}
}{}

\chapter{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?}.
\glspl{EDSL} can have one or more backends or views.
Commonly used views are pretty printing, compiling, simulating, verifying and proving the program.
Embedding techniques can be characterised by at least the following properties:
\begin{enumerate}
	\item Extendibility of constructs
	\item Extendibility of views
	\item Type safety, the type of a term in the language is typed in the host language
	\item Support for well typed variables
	\item Intensional analyses
	\item Support for partial views, not all views need to support all constructs
\end{enumerate}

There are two main techniques for creating embedding \glspl{DSL}, deep---also called tagged---embedding and shallow---also called tagless---embedding.
In the following sections both techniques are explained.
As an example, a simple language with integers, booleans and some arithmetic operators is used as a running example.

\section{Deep embedding}
A deep \gls{EDSL} is a language represented as data in the host language.
Views are functions that transform \emph{something} to the datatype or the other way around.
Definition~\ref{lst:exdeep} shows an implementation for the example \gls{DSL}.

\begin{lstHaskell}[label={lst:exdeep},caption={A deeply embedded expression \gls{DSL}.}]
data Value = I Int | B Bool
data Expr
    = Lit  Value
    | Plus Expr Expr
    | Eq   Expr Expr
  deriving Show
\end{lstHaskell}

Implementing a printer for the language is straightforward:

\begin{lstHaskell}[caption={A printer for the deeply embedded expression \gls{DSL}.}]
print :: Expr -> String
print (Lit i)    = show i
print (Plus l r) = "(" ++ print l ++ "+" ++ print r ++ ")"
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 and \haskellinline{print (Sub l r) = ...} to the \haskellinline{print} view.
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\todo{cite while}.
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.

\begin{lstHaskell}[]
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 $ "Cannot 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 $ "Cannot compare " ++ show l ++ " to " ++ show r
\end{lstHaskell}

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}[]
data Expr a where
    Lit  :: Show a => a -> Expr a
    Plus :: Num a  => Expr a -> Expr a -> Expr a
    Eq   :: Eq a   => Expr a -> Expr a -> Expr Bool

eval :: Expr a -> a
eval (Lit i)    = i
eval (Plus l r) = eval l + eval r
eval (Eq l r)   = eval l == eval r
\end{lstHaskell}

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 \cleaninline{Plus (LitI 4) (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}~\cite{cheney_first-class_2003}.
Example~\ref{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.
However, it has been shown that \glspl{GADT} can be simulated using bimaps or projection pairs~\cite{cheney_first-class_2003}.
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.

\begin{lstClean}[label={lst:exdeepgadt},caption={A deeply embedded expression \gls{DSL} using \glspl{GADT}.}]
:: Expr a
	=      Lit  a                        -> Expr a
	| E.e: Var   String                  -> Expr e
	|      Plus  (Expr Int)  (Expr Int)  -> Expr Int
	| E.e: Eq    (Expr e)    (Expr e)    -> Expr Bool & == e
\end{lstClean}

\subsection{Shallow embedding}
In a shallowly \gls{EDSL} all 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 Definition~\ref{lst:exshallow}.
Note that much of the internals of the language can be hidden using monads.

\begin{lstClean}[label={lst:exshallow}, caption={A minimal shallow \gls{EDSL}.}]
:: Env   :== (String -> Int)
:: DSL a :== (Env -> a)

Lit :: a -> DSL a
Lit x = \e->x

Var :: String -> DSL Int
Var i = \e->retrEnv e i

Plus :: (DSL Int) (DSL Int) -> DSL Int
Plus x y = \e->x e + y e

Eq :: (DSL a) (DSL a) -> DSL Bool | == a
Eq x y = \e->x e == y e
\end{lstClean}

The advantage of shallowly embedding a language in a host language is its extendability.
It is very easy to add functionality because the compile time checks of the host language guarantee whether or not the functionality is available when used.
Moreover, the language is type safe as it is directly typed in the host language, i.e.\ \cleaninline{Lit True +. Lit 4} is rejected.

The downside of this method is extending the language with views.
It is nearly impossible to add views to a shallowly embedded language.
The only way of achieving this is by reimplementing all functions so that they run all backends at the same time.
This will mean that every component will have to implement all views rendering it slow for multiple views and complex to implement.

\subsection{Generalised algebraic data types}

\section{Shallow embedding}

\subsection{Tagless-final embedding}

\section{Comparison}

\input{subfilepostamble}
\end{document}
