many smaller updates
[phd-thesis.git] / dsl / first-class_datatypes.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \include{subfilepreamble}
4
5 \begin{document}
6 \chapter{First-class data types in shallow \glsxtrlongpl{EDSL} using metaprogramming}%
7 \label{chp:first-class_datatypes}%
8 \begin{chapterabstract}
9 \Gls{FP} languages are excellent for hosting \glspl{EDSL} because of their rich type systems, minimal syntax, and referential transparency.
10 However, data types defined in the host language are not automatically available in the embedded language.
11 To do so, all the operations on the data type must be ported to the \gls{EDSL} resulting in a lot of boilerplate.
12
13 This paper shows that by using metaprogramming, all first order user-defined data types can be automatically made first class in shallow \glspl{EDSL}.
14 We show this by providing an implementation in \gls{TH} for a typical \gls{DSL} with two different semantics.
15 Furthermore, we show that by utilising quasiquotation, there is hardly any burden on the syntax.
16 Finally, the paper also serves as a gentle introduction to \gls{TH}.
17 \end{chapterabstract}
18
19 \section{Introduction}
20 \Gls{FP} languages are excellent candidates for hosting \glspl{EDSL} because of their rich type systems, minimal syntax, and referential transparency.
21 By expressing the language constructs in the host language, the parser, the type checker, and the run time can be inherited from the host language.
22 Unfortunately, data types defined in the host language are not automatically available in the \gls{EDSL}.
23
24 The two main strategies for embedding \glspl{DSL} in a \gls{FP} language are deep embedding (also called initial) and shallow embedding (also called final).
25 Deep embedding represents the constructs in the language as data types and the semantics as functions over these data types.
26 This makes extending the language with new semantics effortless: just add another function.
27 In contrast, adding language constructs requires changing the data type and updating all existing semantics to support this new construct.
28 Shallow embedding on the other hand models the language constructs as functions with the semantics embedded.
29 Consequently, adding a construct is easy, i.e.\ it only entails adding another function.
30 Contrarily, adding semantics requires adapting all language constructs.
31 Lifting the functions to type classes, i.e.\ parametrising the constructs over the semantics, allows extension of the language both in constructs and in semantics orthogonally. This advanced style of embedding is called tagless-final or class-based shallow embedding~\citep{kiselyov_typed_2012}.
32
33 While it is often possible to lift values of a user-defined data type to a value in the \gls{DSL}, it is not possible to interact with it using \gls{DSL} constructs, they are not first-class citizens.
34
35 Concretely, it is not possible to
36 \begin{enumerate*}
37 \item construct values from expressions using a constructor,
38 \item deconstruct values into expressions using a deconstructor or pattern matching,
39 \item test which constructor the value holds.
40 \end{enumerate*}
41 The functions for this are simply not available automatically in the embedded language.
42 For some semantics---such as an interpreter---it is possible to directly lift the functions from the host language to the \gls{DSL}.
43 In other cases---e.g.\ \emph{compiling} \glspl{DSL} such as a compiler or a printer---this is not possible~\citep{elliott_compiling_2003}. %the torget this is not possible. cannot just be lifted from the host language to the \gls{DSL} so it requires a lot of boilerplate to define and implement them.
44 Thus, all of the operations on the data type have to be defined by hand requiring a lot of plumbing and resulting in a lot of boilerplate code.
45
46 To relieve the burden of adding all these functions, metaprogramming\nobreak---\nobreak\hskip0pt and custom quasiquoters---can be used.
47 Metaprogramming entails that some parts of the program are generated by a program itself, i.e.\ the program is data.
48 Quasiquotation is a metaprogramming mechanism that allows entering verbatim code for which a---possibly user defined---translation is used to convert the verbatim code to host language AST nodes.
49 Metaprogramming allows functions to be added to the program at compile time based on the structure of user-defined data types.
50
51 \subsection{Contributions of the paper}
52 This paper shows that with the use of metaprogramming, all first-order user-defined data types can automatically be made first class for shallow \glspl{EDSL}.
53 It does so by providing an implementation in \gls{TH} for a typical \gls{DSL} with two different semantics: an interpreter and a pretty printer.
54 Furthermore, we show that by utilising quasiquotation, there is hardly any burden on the syntax.
55 Finally, the paper also serves as a gentle introduction to \gls{TH} and reflects on the process of using \gls{TH}.
56
57 \section{Tagless-final embedding}
58 Tagless-final embedding is an upgrade to standard shallow embedding achieved by lifting all language construct functions to type classes.
59 As a result, views on the \gls{DSL} are data types implementing these classes.
60
61 To illustrate the technique, a simple \gls{DSL}, a language consisting of literals and addition, is outlined.
62 This language, implemented according to the tagless-final style~\citep{carette_finally_2009} in \gls{HASKELL}~\citep{peyton_jones_haskell_2003} consists initially only of one type class containing two functions.
63 The \haskellinline{lit} function lifts values from the host language to the \gls{DSL} domain.
64 The class constraint \haskellinline{Show} is enforced on the type variable \haskellinline{a} to make sure that the value can be printed.
65 The infix function \haskellinline{+.} represents the addition of two expressions in the \gls{DSL}.
66
67 \begin{lstHaskell}
68 class Expr v where
69 lit :: Show a => a -> v a
70 (+.) :: Num a => v a -> v a -> v a
71 infixl 6 +.
72 \end{lstHaskell}
73
74 The implementation of a view on the \gls{DSL} is achieved by implementing the type classes with the data type representing the view.
75 In the case of our example \gls{DSL}, an interpreter accounting for failure may be implemented as an instance for the \haskellinline{Maybe} type.
76 The standard infix functor application and infix sequential application are used so that potential failure is abstracted away from\footnotemark{}.
77 \begin{lrbox}{\LstBox}
78 \begin{lstHaskell}[frame=]
79 <$> :: (a -> b) -> f a -> f b
80 <*> :: f (a -> b) -> f a -> f b
81 infixl 4 <$>, <*>
82 \end{lstHaskell}
83 \end{lrbox}
84 \footnotetext{\usebox{\LstBox}}
85
86 \begin{lstHaskell}
87 instance Expr Maybe where
88 lit a = Just a
89 (+.) l r = (+) <$> l <*> r
90 \end{lstHaskell}
91
92 \subsection{Adding language constructs}
93 To add an extra language construct we define a new class housing it.
94 For example, to add division we define a new class as follows:
95
96 \begin{lstHaskell}
97 class Div v where
98 (/.) :: Integral a => v a -> v a -> v a
99 infixl 7 /.
100 \end{lstHaskell}
101
102 Division is an operation that undefined if the right operand is equal to zero.
103 To capture this behaviour, the \haskellinline{Nothing} constructor from \haskellinline{Maybe} is used to represent errors.
104 The right-hand side of the division operator is evaluated first.
105 If the right-hand side is zero, the division is not performed and an error is returned instead:
106
107 \begin{lstHaskell}
108 instance Div Maybe where
109 (/.) l r = l >>= \x->r >>= \y->
110 if y == 0 then Nothing else Just (x `div` y)
111 \end{lstHaskell}
112
113 \subsection{Adding semantics}
114 To add semantics to the \gls{DSL}, the existing classes are implemented with a novel data type representing the view on the \gls{DSL}.
115 First a data type representing the semantics is defined. In this case, the printer is kept very simple for brevity and just defined as a \haskellinline{newtype} of a string to store the printed representation\footnotemark{}.
116 \footnotetext{%
117 In this case a \haskellinline{newtype} is used instead of regular \haskellinline{data} declarations.
118 \haskellinline{newtype}s are special data types only consisting a single constructor with one field to which the type is isomorphic.
119 During compilation the constructor is completely removed resulting in no overhead~\citep[\citesection{4.2.3}]{peyton_jones_haskell_2003}.
120 }
121 Since the language is typed, the printer data type has to have a type variable but it is only used during typing---i.e.\ a phantom type~\citep{leijen_domain_2000}:
122
123 \begin{lstHaskell}
124 newtype Printer a = P { runPrinter :: String }
125 \end{lstHaskell}
126
127 The class instances for \haskellinline{Expr} and \haskellinline{Div} for the pretty printer are straightforward and as follows:
128
129 \begin{lstHaskell}
130 instance Expr Printer where
131 lit a = P (show a)
132 (+.) l r = P ("(" ++ runPrinter l
133 ++ "+" ++ runPrinter r ++ ")")
134
135 instance Div Printer where
136 (/.) l r = P ("(" ++ runPrinter l
137 ++ "/" ++ runPrinter r ++ ")")
138 \end{lstHaskell}
139
140 \subsection{Functions}
141 Adding functions to the language is achieved by adding a multi-parameter class to the \gls{DSL}.
142 The type of the class function allows for the implementation to only allow first order function by supplying the arguments in a tuple.
143 Furthermore, with the \haskellinline{:-} operator the syntax becomes usable.
144 Finally, by defining the functions as a \gls{HOAS} type safety is achieved~\citep{pfenning_higher-order_1988,chlipala_parametric_2008}.
145 The complete definition looks as follows:
146
147 \begin{lstHaskell}
148 class Function a v where
149 fun :: ((a -> v s) -> In (a -> v s) (v u)) -> v u
150 data In a b = a :- b
151 infix 1 :-
152 \end{lstHaskell}
153
154 Using the \haskellinline{Function} type class can be used to define functions with little syntactic overhead\footnote{The \GHCmod{LambdaCase} extension of GHC is used to reduce the number of brackets that allows lambda's to be an argument to a function without brackets or explicit function application using \haskellinline{\$}}.
155 The following listing shows an expression in the \gls{DSL} utilising two user-defined functions:
156
157 \begin{lstHaskell}
158 fun \increment-> (\x ->x +. lit 1)
159 :- fun \divide-> (\(x, y)->x /. y )
160 :- increment (divide (lit 38, lit 5))
161 \end{lstHaskell}
162
163 The interpreter only requires one instance of the \haskellinline{Function} class that works for any argument type.
164 In the implementation, the resulting function \haskellinline{g} is simultaneously provided to the definition \haskellinline{def}.
165 Because the laziness of \gls{HASKELL}'s lazy let bindings, this results in a fixed point calculation:
166
167 \begin{lstHaskell}
168 instance Function a Maybe where
169 fun def = let g :- m = def g in m
170 \end{lstHaskell}
171
172 The given \haskellinline{Printer} type is not sufficient to implement the instances for the \haskellinline{Function} class, it must be possible to generate fresh function names.
173 After extending the \haskellinline{Printer} type to contain some sort of state to generate fresh function names and a \haskellinline{MonadWriter [String]}\footnotemark{} to streamline the output, we define an instance for every arity.
174 \begin{lrbox}{\LstBox}
175 \begin{lstHaskell}[frame=]
176 freshLabel :: Printer String
177 tell :: MonadWriter w m => w -> m ()
178 \end{lstHaskell}
179 \end{lrbox}
180 \footnotetext{\usebox{\LstBox}}
181 To illustrate this, the instance for unary functions is shown, all other arities are implemented in similar fashion.
182
183 \begin{lstHaskell}
184 instance Function () Printer where ...
185 instance Function (Printer a) Printer where ...
186 fun def = freshLabel >>= \f->
187 let g :- m = def $ \a0->const undefined
188 <$> (tell ["f", show f, " ("]
189 >> a0 >> tell [")"])
190 in tell ["let f", f, " a0 = "]
191 >> g (const undefined <$> tell ["a0"])
192 >> tell [" in "] >> m
193 instance Function (Printer a, Printer b) Printer where ...
194 \end{lstHaskell}
195
196 Running the given printer on the example code shown before produces roughly the following output, running the interpreter on this code results in \haskellinline{Just 8}.
197
198 \begin{lstHaskell}
199 let f0 a1 = a1 + 1
200 in let f2 a3 a4 = a3 / a4
201 in f0 (f2 38 5)
202 \end{lstHaskell}
203
204 \subsection{Data types}
205 Lifting values from the host language to the \gls{DSL} is possible using the \haskellinline{lit} function as long as type of the value has instances for all the class constraints.
206 Unfortunately, once lifted, it is not possible to do anything with values of the user-defined data type other than passing them around.
207 It is not possible to construct new values from expressions in the \gls{DSL}, to deconstruct a value into the fields, nor to test of which constructor the value is.
208 Furthermore, while in the our language the only constraint is the automatically derivable \haskellinline{Show}, in real-world languages the class constraints may be very difficult to satisfy for complex types, for example serialisation to a single stack cell in the case of a compiler.
209
210 As a consequence, for user-defined data types---such as a pro\-gram\-mer-defined list type\footnotemark{}---to become first-class citizens in the \gls{DSL}, language constructs for constructors, deconstructors and constructor predicates must be defined.
211 Field selectors are also useful functions for working with user-defined data types, they are not considered for the sake of brevity but can be implemented using the deconstructor functions.
212 \footnotetext{
213 For example: \haskellinline{data List a = Nil \| Cons \{hd :: a, tl :: List a\}}
214 }
215 The constructs for the list type would result in the following class definition:
216
217 \begin{lstHaskell}
218 class ListDSL v where
219 -- constructors
220 nil :: v (List a)
221 cons :: v a -> v (List a) -> v (List a)
222 -- deconstructors
223 unNil :: v (List a) -> v b -> v b
224 unCons :: v (List a)
225 -> (v a -> v (List a) -> v b) -> v b
226 -- constructor predicates
227 isNil :: v (List a) -> v Bool
228 isCons :: v (List a) -> v Bool
229 \end{lstHaskell}
230
231 Furthermore, instances for the \gls{DSL}'s views need to be created.
232 For example, to use the interpreter, the following instance must be available.
233 Note that at first glance, it would feel natural to have \haskellinline{isNil} and \haskellinline{isCons} return \haskellinline{Nothing} since we are in the \haskellinline{Maybe} monad.
234 However, the this would fail the entire expression and the idea is that the constructor test can be done from within the \gls{DSL}.
235
236 \begin{lstHaskell}
237 instance ListDSL Maybe where
238 nil = Just Nil
239 cons hd tl = Cons <$> hd <*> tl
240 unNil d f = d >>= \Nil->f
241 unCons d f = d
242 >>= \(Cons hd tl)->f (Just hd) (Just tl)
243 isNil d = d >>= \case[+\footnotemark+]
244 Nil -> Just True
245 _ -> Just False
246 isCons d = d >>= \case
247 Cons _ _ -> Just True
248 Nil -> Just False
249 \end{lstHaskell}
250 \footnotetext{%
251 \haskellinline{\\case} is an abbreviation for \haskellinline{\\x->case x of ...} when using GHC's \GHCmod{LambdaCase} extension.
252 }
253
254 Adding these classes and their corresponding instances is tedious and results in boilerplate code.
255 We therefore resort to metaprogramming, and in particular \gls{TH}~\citep{sheard_template_2002} to alleviate this burden.
256
257 \section{Template metaprogramming}
258 Metaprogramming is a special flavour of programming where programs have the ability to treat and manipulate programs or program fragments as data.
259 There are several techniques to facilitate metaprogramming, moreover it has been around for many years now~\citep{lilis_survey_2019}.
260 Even though it has been around for many years, it is considered complex~\citep{sheard_accomplishments_2001}.
261
262 \gls{TH} is GHC's de facto metaprogramming system, implemented as a compiler extension together with a library~\citep{sheard_template_2002}\citep[\citesection{6.13.1}]{ghc_team_ghc_2021}.
263 Readers already familiar with \gls{TH} can safely skip this section.
264
265 \gls{TH} adds four main concepts to the language, na\-me\-ly AST data types, splicing, quasiquotation and reification.
266 With this machinery, regular \gls{HASKELL} functions can be defined that are called at compile time, inserting generated code into the {AST}.
267 These functions are monadic functions operating in the \haskellinline{Q} monad.
268 The \haskellinline{Q} monad facilitates failure, reification and fresh identifier generation for hygienic macros~\citep{kohlbecker_hygienic_1986}.
269 Within the \haskellinline{Q} monad, capturable and non-capturable identifiers can be generated using the \haskellinline{mkName} and \haskellinline{newName} functions respectively.
270 The \emph{Peter Parker principle}\footnote{With great power comes great responsibility.} holds for the \haskellinline{Q} monad as well because it executes at compile time and is very powerful.
271 For example it can subvert module boundaries, thus accessing constructors that were hidden; access the structure of abstract types; and it may cause side effects during compilation because it is possible to call \haskellinline{IO} operations~\citep{terei_safe_2012}.
272 To achieve the goal of embedding data types in a \gls{DSL} we refrain from using these \emph{unsafe} features.
273
274 \subsubsection{Data types}
275 Firstly, for all of \gls{HASKELL}'s AST elements, data types are provided that are mostly isomorphic to the actual data types used in the compiler.
276 With these data types, the entire syntax of a \gls{HASKELL} program can be specified.
277 Often, a data type is suffixed with the context, e.g.\ there is a \haskellinline{VarE} and a \haskellinline{VarP} for a variable in an expression or in a pattern respectively.
278 To give an impression of these data types, a selection of data types available in \gls{TH} is given below:
279
280 \begin{lstHaskell}
281 data Dec = FunD Name [Clause] | DataD Cxt Name ...
282 | SigD Name Type | ClassD Cxt Name | ...
283 data Clause = Clause [Pat] Body [Dec]
284 data Pat = LitP Lit | VarP Name | TupP [Pat]
285 | WildP | ListP [Pat] | ...
286 data Body = GuardedB [(Guard, Exp)] | NormalB Exp
287 data Guard = NormalG Exp | PatG [Stmt]
288 data Exp = VarE Name | LitE Lit | AppE Exp Exp
289 | TupE [Maybe Exp] | LamE [Pat] Exp | ...
290 data Lit = CharL Char | StringL String
291 | IntegerL Integer | ...
292 \end{lstHaskell}
293
294 To ease creating AST data types in the \haskellinline{Q} monad, lowercase variants of the constructors are available that lift the constructor to the \haskellinline{Q} monad as.
295 For example, for the \haskellinline{LamE} constructor, the following \haskellinline{lamE} function is available.
296
297 \begin{lstHaskell}
298 lamE :: [Q Pat] -> Q Exp -> Q Exp
299 lamE ps es = LamE <$> sequence ps <*> es
300 \end{lstHaskell}
301
302 \subsubsection{Splicing}
303 Special splicing syntax (\haskellinline{\$(...)}) marks functions for compile-time execution.
304 Other than that they always produce a value of an AST data type, they are regular functions.
305 Depending on the context and location of the splice, the result type is either a list of declarations, a type, an expression or a pattern.
306 The result of this function, when successful, is then spliced into the code and treated as regular code by the compiler.
307 Consequently, the code that is generated may not be type safe, in which case the compiler provides a type error on the generated code.
308 The following listing shows an example of a \gls{TH} function generating on-the-fly functions for arbitrary field selection in a tuple.
309 When called as \haskellinline{\$(tsel 2 4)} it expands at compile time to \haskellinline{\\(_, _, f, _)->f}:
310
311 \begin{lstHaskell}
312 tsel :: Int -> Int -> Q Exp
313 tsel field total = do
314 f <- newName "f"
315 lamE [ tupP [if i == field then varP f else wildP
316 | i<-[0..total-1]]] (varE f)
317 \end{lstHaskell}
318
319 \subsubsection{Quasiquotation}
320 Another key concept of \gls{TH} is Quasiquotation, the dual of splicing~\citep{bawden_quasiquotation_1999}.
321 While it is possible to construct entire programs using the provided data types, it is a little cumbersome.
322 Using \emph{Oxford brackets} (\verb#[|# \ldots\verb#|]#) or single or double apostrophes, verbatim \gls{HASKELL} code can be entered that is converted automatically to the corresponding AST nodes easing the creation of language constructs.
323 Depending on the context, different quasiquotes are used:
324 \begin{itemize*}
325 \item \haskellinline{[\|...\|]} or \haskellinline{[e\|...\|]} for expressions
326 \item \haskellinline{[d\|...\|]} for declarations
327 \item \haskellinline{[p\|...\|]} for patterns
328 \item \haskellinline{[t\|...\|]} for types
329 \item \haskellinline{'...} for function names
330 \item \haskellinline{''...} for type names
331 \end{itemize*}.
332 It is possible to escape the quasiquotes again by splicing.
333 Variables defined within quasiquotes are always fresh---as if defined with \haskellinline{newName}---but it is possible to capture identifiers using \haskellinline{mkName}.
334 For example, \haskellinline{[|\\x->x|]} translates to \haskellinline{newName "x" >>= \\x->lamE [varP x] (varE x)} and does not interfere with other \haskellinline{x}s already defined.
335
336 \subsubsection{Reification}
337 Reification is the act of querying the compiler for information about a certain name.
338 For example, reifying a type name results in information about the type and the corresponding AST nodes of the type's definition.
339 This information can then be used to generate code according to the structure of data types.
340 Reification is done using the \haskellinline{reify :: Name -> Q Info} function.
341 The \haskellinline{Info} type is an \gls{ADT} containing all the---known to the compiler---information about the matching type: constructors, instances, \etc.
342
343 \section{Metaprogramming for generating \texorpdfstring{\glsxtrshort{DSL}}{DSL} functions}
344 With the power of metaprogramming, we can generate the boilerplate code for our user-defined data types automatically at compile time.
345 To generate the code required for the \gls{DSL}, we define the \haskellinline{genDSL} function.
346 The type belonging to the name passed as an argument to this function is made available for the \gls{DSL} by generating the \haskellinline{typeDSL} class and view instances.
347 For the \haskellinline{List} type it is called as: \haskellinline{\$(genDSL ''List)}\footnotemark{}.
348 \footnotetext{
349 \haskellinline{''} is used instead of \haskellinline{'} to instruct the compiler to look up the information for \haskellinline{List} as a type and not as a constructor.
350 }
351
352 The \haskellinline{genDSL} function is a regular function---though \gls{TH} requires that it is defined in a separate module---that has type: \haskellinline{Name -> Q [Dec]}, i.e.\ given a name, it produces a list of declarations in the \haskellinline{Q} monad.
353 The \haskellinline{genDSL} function first reifies the name to retrieve the structural information.
354 If the name matches a type constructor containing a data type declaration, the structure of the type---the type variables, the type name and information about the constructors\footnotemark{}---are passed to the \haskellinline{genDSL'} function.
355 \footnotetext{
356 Defined as \haskellinline{type VarBangType = (Name, Bang, Type)} by \gls{TH}.
357 }
358 The \haskellinline{getConsName} function filters out unsupported data types such as \glspl{GADT} and makes sure that every field has a name.
359 For regular \glspl{ADT}, the \haskellinline{adtFieldName} function is used to generate a name for the constructor based on the indices of the fields\footnotemark{}.
360 \footnotetext{
361 \haskellinline{adtFieldName :: Name -> Integer -> Name}
362 }
363 From this structure of the type, \haskellinline{genDSL'} generates a list of declarations containing a class definition (\cref{sec_fcd:class}), instances for the interpreter (\cref{sec_fcd:interpreter}), and instances of the printer (\cref{sec_fcd:prettyprinter}) respectively.
364
365 \begin{lstHaskell}
366 genDSL :: Name -> Q [Dec]
367 genDSL name = reify name >>= \case
368 TyConI (DataD cxt typeName tvs mkind
369 constructors derives)
370 -> mapM getConsName constructors
371 >>= \d->genDSL' tvs typeName d
372 t -> fail ("genDSL does not support: " ++ show t)
373
374 getConsName :: Con -> Q (Name, [VarBangType])
375 getConsName (NormalC consName fs) = pure (consName,
376 [(adtFieldName consName i, b, t)
377 | (i, (b, t))<-[0..] `zip` fs])
378 getConsName (RecC consName fs) = pure (consName, fs)
379 getConsName c
380 = fail ("genDSL does not support: " ++ show c)
381
382 genDSL' :: [TyVarBndr] -> Name -> [(Name, [VarBangType])]
383 -> Q [Dec]
384 genDSL' typeVars typeName constructors = sequence
385 [ mkClass, mkInterpreter, mkPrinter, ... ]
386 where
387 (consNames, fields) = unzip constructors
388 ...
389 \end{lstHaskell}
390
391 \subsection{Class generation}\label{sec_fcd:class}
392 The function for generating the class definition is defined in the \haskellinline{where} clause of the \haskellinline{genDSL'} function.
393 Using the \haskellinline{classD} constructor, a single type class is created with a single type variable \haskellinline{v}.
394 The \haskellinline{classD} function takes five arguments:
395 \begin{enumerate*}
396 \item a context, i.e.\ the class constraints, which is empty in this case
397 \item a name, generated from the type name using the \haskellinline{className} function that simply appends the text \haskellinline{DSL}
398 \item a list of type variables, in this case the only type variable is the view on the \gls{DSL}, i.e.\ \haskellinline{v}
399 \item functional dependencies, empty in our case
400 \item a list of function declarations, i.e.\ the class members, in this case it is a concatenation of the constructors, deconstructors, and constructor predicates
401 \end{enumerate*}
402 Depending on the required information, either \haskellinline{zipWith} or \haskellinline{map} is used to apply the generation function to all constructors.
403
404 \begin{lstHaskell}
405 mkClass :: Q Dec
406 mkClass = classD (cxt []) (className typeName) [PlainTV (mkName "v")] []
407 ( zipWith mkConstructor consNames fields
408 ++ zipWith mkDeconstructor consNames fields
409 ++ map mkPredicate consNames
410 )
411 \end{lstHaskell}
412
413 In all class members, the view \haskellinline{v} plays a crucial role.
414 Therefore, a definition for \haskellinline{v} is accessible for all generation functions.
415 Furthermore, the \haskellinline{res} type represents the \emph{result} type, it is defined as the type including all type variables.
416 This result type is derived from the type name and the list of type variables.
417 In case of the \haskellinline{List} type, \haskellinline{res} is defined as \haskellinline{v (List a)} and is available for as well:
418
419 \begin{lstHaskell}
420 v = varT (mkName "v")
421 res = v `appT` foldl appT (conT typeName)
422 (map getName typeVars)
423 where getName (PlainTV name) = varT name
424 getName (KindedTV name _) = varT name
425 \end{lstHaskell}
426
427 \subsubsection{Constructors}
428 The constructor definitions are generated from just the constructor names and the field information.
429 All class members are defined using the \haskellinline{sigD} constructor that represents a function signature.
430 The first argument is the name of the constructor function, a lowercase variant of the actual constructor name generated using the \haskellinline{constructorName} function.
431 The second argument is the type of the function.
432 A constructor $C_k$ of type $T$ where
433 $T~tv_0~\ldots~tv_n = \ldots |~ C_k~a_0~\ldots~a_m~| \ldots~$
434 is defined as a \gls{DSL} function
435 $c_k \dcolon v~a_0 \shortrightarrow \ldots \shortrightarrow v~a_m \shortrightarrow v~(T~v_0~\ldots~v_n) $.
436 In the implementation, first the view \haskellinline{v} is applied to all the field types.
437 Then, the constructor type is constructed by folding over the lifted field types with the result type as the initial value using \haskellinline{mkCFun}.
438
439 \begin{lstHaskell}
440 mkConstructor :: Name -> [VarBangType] -> Q Dec
441 mkConstructor n fs
442 = sigD (constructorName n) (mkCFun fs res)
443
444 mkCFun :: [VarBangType] -> Q Type -> Q Type
445 mkCFun fs res = foldr (\x y->[t|$x -> $y|])
446 (map (\(_, _, t)->v `appT` pure t) fs)
447 \end{lstHaskell}
448
449 \subsubsection{Deconstructors}
450 The deconstructor is generated similarly to the constructor as the function for generating the constructor is the second argument modulo change in the result type.
451 A deconstructor $C_k$ of type $T$ is defined as a \gls{DSL} function
452 $\mathit{unC_k} \dcolon v~(T~v_0 \ldots v_n) \shortrightarrow (v~a_0 \shortrightarrow \ldots \shortrightarrow v~a_m \shortrightarrow v~b) \shortrightarrow v~b $.
453 In the implementation, \haskellinline{mkCFun} is reused to construct the type of the deconstructor as follows:
454
455 \begin{lstHaskell}
456 mkDeconstructor :: Name -> [VarBangType] -> Q Dec
457 mkDeconstructor n fs = sigD (deconstructorName n)
458 [t|$res -> $(mkCFun fs [t|$v $b|]) -> $v $b|]
459 where b = varT (mkName "b")
460 \end{lstHaskell}
461
462 \subsubsection{Constructor predicates}
463 The last part of the class definition are the constructor predicates, a function that checks whether the provided value of type $T$ contains a value with constructor $C_k$.
464 A constructor predicate for constructor $C_k$ of type $T$ is defined as a \gls{DSL} function $\mathit{isC_k} \dcolon v~(T~v_0~\ldots~v_n) \shortrightarrow v~\mathit{Bool}$.
465 A constructor predicate---name prefixed by \haskellinline{is}---is generated for all constructors.
466 They all have the same type:
467
468 \begin{lstHaskell}
469 mkPredicate :: Name -> Q Dec
470 mkPredicate n = sigD (predicateName n)
471 [t|$res -> $v Bool|]
472 \end{lstHaskell}
473
474 \subsection{Interpreter instance generation}\label{sec_fcd:interpreter}
475 Generating the interpreter for the \gls{DSL} means generating the class instance for the \haskellinline{Interpreter} data type using the \haskellinline{instanceD} function.
476 The first argument of the instance is the context, this is left empty.
477 The second argument of the instance is the type, the \haskellinline{Interpreter} data type applied to the class name.
478 Finally, the class function instances are generated using the information derived from the structure of the type.
479 The structure for generating the function instances is very similar to the class definition, only for the function instances of the constructor predicates, the field information is required as well as the constructor names.
480
481 \begin{lstHaskell}
482 mkInterpreter :: Q Dec
483 mkInterpreter = instanceD (cxt [])
484 [t|$(conT (className typeName)) Interpreter|]
485 ( zipWith mkConstructor consNames fields
486 ++ zipWith mkDeconstructor consNames fields
487 ++ zipWith mkPredicate consNames fields)
488 where ...
489 \end{lstHaskell}
490
491 \subsubsection{Constructors}
492 The interpreter is a view on the \gls{DSL} that immediately executes all operations in the \haskellinline{Maybe} monad.
493 Therefore, the constructor function can be implemented by lifting the actual constructor to the \haskellinline{Maybe} type using sequential application.
494 I.e.\ for a constructor $C_k$ this results in the following constructor: \haskellinline{ck a0 ... am = pure Ck <*> a0 <*> ... <*> am}.
495 To avoid accidental shadowing, fresh names for all the arguments are generated.
496 The \haskellinline{ifx} function is used as a shorthand for defining infix expressions\footnotemark{}
497 \begin{lrbox}{\LstBox}
498 \begin{lstHaskell}[frame=]
499 ifx :: String -> Q Exp -> Q Exp -> Q Exp
500 ifx op a b = infixE (Just a) (varE (mkName op)) (Just b)
501 \end{lstHaskell}
502 \end{lrbox}
503 \footnotetext{\usebox{\LstBox}}
504
505 \begin{lstHaskell}
506 mkConstructor :: Name -> [VarBangType] -> Q Dec
507 mkConstructor consName fs = do
508 fresh <- sequence [newName "a" | _<-fs]
509 fun (constructorName consName) (map varP fresh)
510 (foldl (ifx "<*>") [|pure $(conE consName)|]
511 (map varE fresh))
512 \end{lstHaskell}
513
514
515 \subsubsection{Deconstructors}
516 In the case of a deconstructor a function with two arguments is created: the object itself (\haskellinline{f}) and the function doing something with the individual fields (\haskellinline{d}).
517 To avoid accidental shadowing first fresh names for the arguments and fields are generated.
518 Then, a function is created with the two arguments.
519 First \haskellinline{d} is evaluated and bound to a host language function that deconstructs the constructor and passes the fields to \haskellinline{f}.
520 I.e.\ a deconstructor function $C_k$ is defined as: \haskellinline{unCk d f = d >>= \\(Ck a0 .. am)->f (pure a0) ... (pure am))}\footnotemark{}.
521 \footnotetext{
522 The \haskellinline{nameBase :: Name -> String} function from the \gls{TH} library is used to convert a name to a string.
523 }
524
525 \begin{lstHaskell}
526 mkDeconstructor :: Name -> [VarBangType] -> Q Dec
527 mkDeconstructor consName fs = do
528 d <- newName "d"
529 f <- newName "f"
530 fresh <- mapM (newName . nameBase . fst3) fs
531 fun (deconstructorName consName) [varP d, varP f]
532 [|$(varE d) >>= \($(match f))->$(fapp f fresh)|]
533 where fapp f = foldl appE (varE f)
534 . map (\f->[|pure $(varE f)|])
535 match f = pure (ConP consName (map VarP f))
536 \end{lstHaskell}
537
538 \subsubsection{Constructor predicates}
539 Constructor predicates evaluate the argument and make a case distinction on the result to determine the constructor.
540 To be able to generate a valid pattern in the case distinction, the total number of fields must be known.
541 To avoid having to explicitly generate a fresh name for the first argument, a lambda function is used.
542 In general, the constructor selector for $C_k$ results in the following code \haskellinline{isCk f = f >>= \\case Ck _ ... _ -> pure True; _ -> pure False}.
543 Generating this code is done with the following function:
544
545 \begin{lstHaskell}
546 mkPredicate :: Name -> [(Var, Bang, Type)] -> Q Dec
547 mkPredicate n fs = fun (predicateName n) []
548 [|\x->x >>= \case
549 $(conP n [wildP | _<-fs]) -> pure True
550 _ -> pure False|]
551 \end{lstHaskell}
552
553 \subsection{Pretty printer instance generation}\label{sec_fcd:prettyprinter}
554 Generating the printer happen analogously to the interpreter, a class instance for the \haskellinline{Printer} data type using the \haskellinline{instanceD} function.
555
556 \begin{lstHaskell}
557 mkPrinter :: Q Dec
558 mkPrinter = instanceD (cxt []) [t|$(conT (className typeName)) Printer|]
559 ( zipWith mkConstructor consNames fields
560 ++ zipWith mkDeconstructor consNames fields
561 ++ map mkPredicate consNames)
562 \end{lstHaskell}
563
564 To be able to define a printer that is somewhat more powerful, we provide instances for \haskellinline{MonadWriter}; add a state for fresh variables and a context; and define some helper functions the \haskellinline{Printer} datatype.
565 The \haskellinline{printLit} function is a variant of \haskellinline{MonadWriter}s \haskellinline{tell} that prints a literal string but it can be of any type (it is a phantom type anyway).
566 \haskellinline{printCons} prints a constructor name followed by an expression, it inserts parenthesis only when required depending on the state.
567 \haskellinline{paren} always prints parenthesis around the given printer.
568 \haskellinline{>->} is a variant of the sequence operator \haskellinline{>>} from the \haskellinline{Monad} class, it prints whitespace in between the arguments.
569
570 \begin{lstHaskell}
571 printLit :: String -> Printer a
572 printCons :: String -> Printer a -> Printer a
573 paren :: Printer a -> Printer a
574 (>->) :: Printer a1 -> Printer a2 -> Printer a3
575 pl :: String -> Q Exp
576 \end{lstHaskell}
577
578 \subsubsection{Constructors}
579 For a constructor $C_k$ the printer is defined as: \haskellinline{ck a0 ... am = printCons "Ck" (printLit "" >-> a0 >-> ... >-> am)}.
580 To generate the second argument to the \haskellinline{printCons} function, a fold is used with \haskellinline{printLit ""} as the initial element to account for constructors without any fields as well, e.g.\ \haskellinline{Nil} is translated to \haskellinline{nil = printCons "Nil" (printLit "")}.
581
582 \begin{lstHaskell}
583 mkConstructor :: Name -> [VarBangType] -> Q Dec
584 mkConstructor consName fs = do
585 fresh <- sequence [newName "f" | _<- fs]
586 fun (constructorName consName) (map varP fresh)
587 (pcons `appE` pargs fresh)
588 where pcons = [|printCons $(lift (nameBase consName))|]
589 pargs fresh = foldl (ifx ">->") (pl "")
590 (map varE fresh)
591 \end{lstHaskell}
592
593 \subsubsection{Deconstructors}
594 Printing the deconstructor for $C_k$ is defined as:
595 \begin{lstHaskell}
596 unCk d f
597 = printLit "unCk d"
598 >-> paren (
599 printLit "\(Ck" >-> printLit "a0 ... am" >> printLit ")->"
600 >> f (printLit "a0") ... (printLit "am")
601 )
602 \end{lstHaskell}
603
604 The implementation for this is a little elaborate and it heavily uses the \haskellinline{pl} function, a helper function that translates a string literal \haskellinline{s} to \haskellinline{[|printLit \$(lift s)|]}, i.e.\ it lifts the \haskellinline{printLit} function to the \gls{TH} domain.
605
606 \begin{lstHaskell}
607 mkDeconstructor :: Name -> [VarBangType] -> Q Dec
608 mkDeconstructor consName fs = do
609 d <- newName "d"
610 f <- newName "f"
611 fresh <- sequence [newName "a" | _<-fs]
612 fun (deconstructorName consName) (map varP [d, f])
613 [| $(pl (nameBase (deconstructorName consName)))
614 >-> $(pl (nameBase d))
615 >-> paren ($(pl ('\\':'(':nameBase consName))
616 >-> $lam >> printLit ")->"
617 >> $(hoas f))|]
618 where
619 lam = pl $ unwords [nameBase f | (f, _, _)<-fs]
620 hoas f = foldl appE (varE f)
621 [pl (nameBase f) | (f, _, _)<-fs]
622 \end{lstHaskell}
623
624 \subsubsection{Constructor predicates}
625 For the printer, the constructor selector for $C_k$ results in the following code \haskellinline{isCk f = printLit "isCk" >-> f}.
626
627 \begin{lstHaskell}
628 mkPredicate :: Name -> Q Dec
629 mkPredicate n = fun (predicateName n) []
630 [|\x-> $(pl $ nameBase $ predicateName n) >-> x|]
631 \end{lstHaskell}
632
633 \section{Pattern matching}
634 It is possible to construct and deconstruct values from other \gls{DSL} expressions, and to perform tests on the constructor but with a clunky and unwieldy syntax.
635 They have become first-class citizens in a grotesque way.
636 For example, given that we have some language constructs to denote failure and conditionals\footnotemark{}, writing a list summation function in our \gls{DSL} would be done as follows.
637 For the sake of the argument we take a little shortcut here and assume that the interpretation of the \gls{DSL} supports lazy evaluation by using the host language as a metaprogramming language as well, allowing us to use functions in the host language to contstruct expressions in the \gls{DSL}.
638
639 \begin{lrbox}{\LstBox}
640 \begin{lstHaskell}[frame=]
641 class Support v where
642 if' :: v Bool -> v a -> v a -> v a
643 bottom :: String -> v a
644 \end{lstHaskell}
645 \end{lrbox}
646 \footnotetext{\usebox{\LstBox}}
647
648 \begin{lstHaskell}
649 program :: (ListDSL v, Support v, ...) => v Int
650 program
651 = fun \sum->(\l->if'(isNil l)
652 (lit 0)
653 (unCons l (\hd tl->hd +. sum tl)))
654 :- sum (cons (lit 38) (cons (lit 4) nil))
655 \end{lstHaskell}
656
657 A similar \gls{HASKELL} implementation is much more elegant and less cluttered because of the support for pattern matching.
658 Pattern matching offers a convenient syntax for doing deconstruction and constructor tests at the same time.
659
660 \begin{lstHaskell}
661 sum :: List Int -> Int
662 sum Nil = 0
663 sum (List hd tl) = hd + sum tl
664
665 main = sum (Cons 38 (Cons 4 Nil))
666 \end{lstHaskell}
667
668 \subsection{Custom quasiquoters}
669 The syntax burden of \glspl{EDSL} can be reduced using quasiquotation.
670 In \gls{TH}, quasiquotation is a convenient way to create \gls{HASKELL} language constructs by entering them verbatim using Oxford brackets.
671 However, it is also possible to create so-called custom quasiquoters~\citep{mainland_why_2007}.
672 If the programmer writes down a fragment of code between tagged \emph{Oxford brackets}, the compiler executes the associated quasiquoter functions at compile time.
673 A quasiquoter is a value of the following data type:
674
675 \begin{lstHaskell}
676 data QuasiQuoter = QuasiQuoter
677 { quoteExp :: String -> Q Exp
678 , quotePat :: String -> Q Pat
679 , quoteType :: String -> Q Type
680 , quoteDec :: String -> Q Dec
681 }
682 \end{lstHaskell}
683
684 The code between \emph{dsl} brackets (\haskellinline{[dsl\|...\|]}) is preprocessed by the \haskellinline{dsl} quasiquoter.
685 Because the functions are executed at compile time, errors---thrown using the \haskellinline{MonadFail} instance of the \haskellinline{Q} monad---in these functions result in compile time errors.
686 The AST nodes produced by the quasiquoter are inserted into the location and checked as if they were written by the programmer.
687
688 To illustrate writing a custom quasiquoter, we show an implementation of a quasiquoter for binary literals.
689 The \haskellinline{bin} quasiquoter is only defined for expressions and parses subsequent zeros and ones as a binary number and splices it back in the code as a regular integer.
690 Thus, \haskellinline{[bin\|101010\|]} results in the literal integer expression \haskellinline{42}.
691 If an invalid character is used, a compile-time error is shown.
692 The quasiquoter is defined as follows:
693
694 \begin{lstHaskell}
695 bin :: QuasiQuoter
696 bin = QuasiQuoter { quoteExp = parseBin }
697 where
698 parseBin :: String -> Q Exp
699 parseBin s = LitE . IntegerL <$> foldM bindigit 0 s
700
701 bindigit :: Integer -> Char -> Q Integer
702 bindigit acc '0' = pure (2 * acc)
703 bindigit acc '1' = pure (2 * acc + 1)
704 bindigit acc c = fail ("invalid char: " ++ show c)
705 \end{lstHaskell}
706
707 \subsection{Quasiquotation for pattern matching}
708 Custom quasiquoters allow the \gls{DSL} user to enter fragments verbatim, bypassing the syntax of the host language.
709 Pattern matching in general is not suitable for a custom quasiquoter because it does not really fit in one of the four syntactic categories for which custom quasiquoter support is available.
710 However, a concrete use of pattern matching, interesting enough to be beneficial, but simple enough for a demonstration is the \emph{simple case expression}, a case expression that does not contain nested patterns and is always exhaustive.
711 They correspond to a multi-way conditional expressions and can thus be converted to \gls{DSL} constructs straightforwardly~\citep[\citesection{4.4}]{peyton_jones_implementation_1987}.
712
713 In contrast to the binary literal quasiquoter example, we do not create the parser by hand.
714 The parser combinator library \emph{parsec} is used instead to ease the creation of the parser~\citep{leijen_parsec_2001}.
715 First the location of the quasiquoted code is retrieved using the \haskellinline{location} function that operates in the \haskellinline{Q} monad.
716 This location is inserted in the parsec parser so that errors are localised in the source code.
717 Then, the \haskellinline{expr} parser is called that returns an \haskellinline{Exp} in the \haskellinline{Q} monad.
718 The \haskellinline{expr} parser uses parsec's commodity expression parser primitive \haskellinline{buildExpressionParser}.
719 The resulting parser translates the string directly into \gls{TH}'s AST data types in the \haskellinline{Q} monad.
720 The most interesting parser is the parser for the case expression that is an alternative in the basic expression parser \haskellinline{basic}.
721 A case expression is parsed when a keyword \haskellinline{case} is followed by an expression that is in turn followed by a non-empty list of matches.
722 A match is parsed when a pattern (\haskellinline{pat}) is followed by an arrow and an expression.
723 The results of this parser are fed into the \haskellinline{mkCase} function that transforms the case into an expression using \gls{DSL} primitives such as conditionals, deconstructors and constructor predicates.
724 The above translates to the following skeleton implementation:
725
726 \begin{lstHaskell}
727 expr :: Parser (Q Exp)
728 expr = buildExpressionParser [...] basic
729 where
730 basic :: Parser (Q Exp)
731 basic = ...
732 <|> mkCase <$ reserved "case" <*> expr
733 <* reserved "of" <*> many1 match
734 <|> ...
735
736 match :: Parser (Q Pat, Q Exp)
737 match = (,) <$> pat <* reserved "->" <*> expr
738
739 pat :: Parser (Q Pat)
740 pat = conP <$> con <*> many var
741 \end{lstHaskell}
742
743 Case expressions are transformed into constructors, deconstructors and constructor predicates, e.g.\ \haskellinline{case e1 of Cons hd tl -> e2; Nil -> e3;} is converted to:
744 \begin{lstHaskell}
745 if' (isList e1)
746 (unCons e1 (\hd tl->e2))
747 (if' (isNil e1)
748 (unNil e1 e3)
749 (bottom "Exhausted case"))
750 \end{lstHaskell}
751
752 The \haskellinline{mkCase} (\cref{mkcase_fcd:mkcase}) function transforms a case expression into constructors, deconstructors and constructor predicates.
753 \Cref{mkcase_fcd:eval} first evaluates the patterns.
754 Then the patterns and their expressions are folded using the \haskellinline{mkCase`} function (\cref{mkcase_fcd:pairs}).
755 While a case exhaustion error is used as the initial value, this is never called since all case expressions are exhaustive.
756 For every case, code is generated that checks whether the constructor used in the pattern matches the constructor of the value using constructor predicates (\cref{mkcase_fcd:conspred}).
757 If the constructor matches, the deconstructor (\cref{mkcase_fcd:consdec}) is used to bind all names to the correct identifiers and evaluate the expression.
758 If the constructor does not match, the continuation (\haskellinline{\$rest}) is used (\cref{mkcase_fcd:consstart}).
759
760 \begin{lstHaskell}[numbers=left]
761 mkCase :: Q Exp -> [(Q Pat, Q Exp)] -> Q Exp [+\label{mkcase_fcd:mkcase} +]
762 mkCase name cases = do
763 pats <- mapM fst cases [+ \label{mkcase_fcd:eval} +]
764 foldr (uncurry mkCase') [|bottom "Exhausted case"|][+ \label{mkcase_fcd:fold}\label{mkcase_fcd:foldinit} +]
765 (zip pats (map snd cases)) [+\label{mkcase_fcd:pairs}+]
766 where
767 mkCase' :: Pat -> Q Exp -> Q Exp -> Q Exp
768 mkCase' (ConP cons fs) e rest
769 = [|if' $pred $then_ $rest|] [+\label{mkcase_fcd:consstart}+]
770 where
771 pred = varE (predicateName cons) `appE` name[+\label{mkcase_fcd:conspred}+]
772 then_ = [|$(varE (deconstructorName cons))[+\label{mkcase_fcd:consdec}+]
773 $name $(lamE [pure f | f<-fs] e)|][+\label{mkcase_fcd:consend}+]
774 \end{lstHaskell}
775
776 Finally, with this quasiquotation mechanism we can define our list summation using a case expression.
777 As a byproduct, syntactic cruft such as the special symbols for the operators and calls to \haskellinline{lit} can be removed as well resulting in the following summation implementation:
778
779 \begin{lstHaskell}
780 program :: (ListDSL v, DSL v, ...) => v Int
781 program
782 = fun \sum->(\l->[dsl|case l of
783 Cons hd tl -> hd + sum tl
784 Nil -> 0|])
785 :- sum (cons (lit 38) (cons (lit 4) nil))
786 \end{lstHaskell}
787
788 \section{Related work}
789 Generic or polytypic programming is a promising technique at first glance for automating the generation of function implementations~\citep{lammel_scrap_2003}.
790 However, while it is possible to define a function that works on all first-order types, adding a new function with a new name to the language is not possible.
791 This does not mean that generic programming is not useable for embedding pattern matches.
792 In generic programming, types are represented as sums of products and using this representation it is possible to define pattern matching functions.
793
794 For example, \citet{rhiger_type-safe_2009} showed a method for expressing statically typed pattern matching using typed higher-order functions.
795 If not the host language but the \gls{DSL} contains higher order functions, the same technique could be applied to port pattern matching to \glspl{DSL} though using an explicit sums of products representation.
796 \Citeauthor{atkey_unembedding_2009} describe embedding pattern matching in a \gls{DSL} by giving patterns an explicit representation in the \gls{DSL} by using pairs, sums and injections~\citep[\citesection{3.3}]{atkey_unembedding_2009}.
797
798 \Citet{mcdonell_embedded_2022} extends on this idea, resulting in a very similar but different solution to ours.
799 They used the technique that \citeauthor{atkey_unembedding_2009} showed and applied it to deep embedding using the concrete syntax of the host language.
800 The scaffolding---e.g.\ generating the pairs, sums and injections---for embedding is automated using generics but the required pattern synonyms are generated using \gls{TH}.
801 The key difference to our approach is that we specialise the implementation for each of the backends instead of providing a general implementation of data type handling operations.
802 Furthermore, our implementation does not require a generic function to trace all constructors, resulting in problems with (mutual) recursion.
803
804 \Citet{young_adding_2021} added pattern matching to a deeply \gls{EDSL} using a compiler plugin.
805 This plugin implements an \haskellinline{externalise :: a -> E a} function that allows lifting all machinery required for pattern matching automatically from the host language to the \gls{DSL}.
806 Under the hood, this function translates the pattern match to constructors, deconstructors, and constructor predicates.
807 The main difference with this work is that it requires a compiler plugin while our metaprogramming approach works on any compiler supporting a metaprogramming system similar to \gls{TH}.
808
809 \subsection{Related work on \texorpdfstring{\glsxtrlong{TH}}{Template Haskell}}
810 Metaprogramming in general is a very broad research topic and has been around for years already.
811 We therefore do not claim an exhaustive overview of related work on all aspects of metaprogramming.
812 However, we have have tried to present most research on metaprogramming in \gls{TH}.
813 \Citet{czarnecki_dsl_2004} provide a more detailed comparison of different metaprogramming techniques.
814 They compare staged interpreters, metaprogramming and templating by comparing MetaOCaml, \gls{TH} and \gls{CPP} templates.
815 \gls{TH} has been used to implement related work.
816 They all differ slightly in functionality from our domain and can be divided into several categories.
817
818 \subsubsection{Generating extra code}
819 Using \gls{TH} or other metaprogramming systems it is possible to add extra code to your program.
820 The original \gls{TH} paper showed that it is possible to create variadic functions such as \haskellinline{printf} using \gls{TH} that would be almost impossible to define without~\citep{sheard_template_2002}.
821 \Citet{hammond_automatic_2003} used \gls{TH} to generate parallel programming skeletons.
822 In practise, this means that the programmer selects a skeleton and, at compile time, the code is massaged to suit the pattern and information about the environment is inlined for optimisation.
823
824 \Citet{polak_automatic_2006} implemented automatic GUI generation using \gls{TH}.
825 \Citet{duregard_embedded_2011} wrote a parser generator using \gls{TH} and the custom quasiquoting facilities.
826 From a specification of the grammar, given in verbatim using a custom quasiquoter, a parser is generated at compile time.
827 \Citet{shioda_libdsl_2014} used metaprogramming in the D programming language to create a \gls{DSL} toolkit.
828 They also programmatically generate parsers and a backend for either compiling or interpreting the \gls{IR}.
829 \Citet{blanchette_liquid_2022} use \gls{TH} to simplify the development of Liquid \gls{HASKELL} proofs.
830 \Citet{folmer_high-level_2022} used \gls{TH} to synthesize C$\lambda$aSH~\citep{baaij_digital_2015} abstract syntax trees to be processed.
831 In similar fashion, \citet{materzok_generating_2022} used \gls{TH} to translate YieldFSM programs to {C$\lambda$aSH}.
832
833 \subsubsection{Optimisation}
834 Besides generating code, it is also possible to analyse existing code and perform optimisations.
835 Yet, this is dangerous territory because unwantedly the semantics of the optimised program may be slightly different from the original program.
836 For example, \citet{lynagh_unrolling_2003} implemented various optimisations in \gls{TH} such as automatic loop unrolling.
837 The compile-time executed functions analyse the recursive function and unroll the recursion to a fixed depth to trade execution speed for program space.
838 Also, \citet{odonnell_embedding_2004} embedded Hydra, a hardware description language, in \gls{HASKELL} utilising \gls{TH}.
839 Using intensional analysis of the AST, it detects cycles by labelling nodes automatically so that it can generate \emph{netlists}.
840 The authors mention that alternatively this could have be done using a monad but this hampers equational reasoning greatly, which is a key property of Hydra.
841 Finally, \citet{viera_staged_2018} present a way of embedding attribute grammars in \gls{HASKELL} in a staged fashion.
842 Checking several aspects of the grammar is done at compile time using \gls{TH} while other safety checks are performed at runtime.
843
844 \subsubsection{Compiler extension}
845 Sometimes, expressing certain functionalities in the host languages requires a lot of boilerplate, syntax wrestling, or other pains.
846 Metaprogramming can relieve some of this stress by performing this translation to core constructs automatically.
847 For example, implementing generic---or polytypic--- functions in the compiler is a major effort.
848 \Citet{norell_prototyping_2004} used \gls{TH} to implement the machinery required to implement generic functions at compile time.
849 \Citet{adams_template_2012} also explores implementing generic programming using \gls{TH} to speed things up considerably compared to regular generic programming.
850 \Citet{clifton-everest_embedding_2014} use \gls{TH} with a custom quasiquoter to offer skeletons for workflows and embed foreign function interfaces in a \gls{DSL}.
851 \Citet{eisenberg_promoting_2014} showed that it is possible to programmatically lift some functions from the function domain to the type domain at compile time, i.e.\ type families.
852 Furthermore, \citet{seefried_optimising_2004} argued that it is difficult to do some optimisations in \glspl{EDSL} and that metaprogramming can be of use there.
853 They use \gls{TH} to change all types to unboxed types, unroll loops to a certain depth and replace some expressions by equivalent more efficient ones.
854 \Citet{torrano_strictness_2005} showed that it is possible to use \gls{TH} to perform a strictness analysis and perform let-to-case translation.
855 Both applications are examples of compiler extensions that can be implemented using \gls{TH}.
856 Another example of such a compiler extension is shown by \citet{gill_haskell_2009}.
857 They created a meta level \gls{DSL} to describe rewrite rules on \gls{HASKELL} syntax that are applied on the source code at compile time.
858
859 \subsubsection{Quasiquotation}
860 By means of quasiquotation, the host language syntax that usually seeps through the embedding can be hidden.
861 The original \gls{TH} quasiquotation paper~\citep{mainland_why_2007} shows how this can be done for regular expressions, not only resulting in a nicer syntax but syntax errors are also lifted to compile time instead of run time.
862 Also, \citet{kariotis_making_2008} used \gls{TH} to automatically construct monad stacks without having to resort to the monad transformers library which requires advanced type system extensions.
863
864 \Citet{najd_everything_2016} uses the compile time to be able to do normalisation for a \gls{DSL}, dubbing it \glspl{QDSL}.
865 They utilise the quasiquation facilities of \gls{TH} to convert \gls{HASKELL} \gls{DSL} code to constructs in the \gls{DSL}, applying optimisations such as eliminating lambda abstractions and function applications along the way.
866 \Citet{egi_embedding_2022} extended \gls{HASKELL} to support non-free data type pattern matching---i.e.\ data type with no standard form, e.g.\ sets, graphs---using \gls{TH}.
867 Using quasiquotation, they make a complicated embedding of non-linear pattern matching available through a simple lens.
868
869 \subsubsection{\texorpdfstring{\glsxtrlong{TTH}}{Typed Template Haskell}}\label{ssec_fcd:typed_template_haskell}
870 \gls{TTH} is a very recent extension/alternative to normal \gls{TH}~\citep{pickering_multi-stage_2019,xie_staging_2022}.
871 Where in \gls{TH} you can manipulate arbitrary parts of the syntax tree, add top-level splices of data types, definitions and functions, in \gls{TTH} the programmer can only splice expressions but the abstract syntax tree fragments representing the expressions are well-typed by construction instead of untyped.
872
873 \Citet{pickering_staged_2020} implemented staged compilation for the \emph{generics-sop}~\citep{de_vries_true_2014} generics library to improve the efficiency of the code using \gls{TTH}.
874 \Citet{willis_staged_2020} used \gls{TTH} to remove the overhead of parsing combinators.
875
876 \section{Discussion}
877 This paper aims to be twofold, first, it shows how to inherit data types in a \gls{DSL} as first-class citizens by generating the boilerplate at compile time using \gls{TH}.
878 Secondly, it introduces the reader to \gls{TH} by giving an overview of the literature in which \gls{TH} is used and provides a gentle introduction by explaining the case study.
879
880 \Gls{FP} languages are especially suitable for embedding \glspl{DSL} but adding user-defined data types is still an issue.
881 The tagless-final style of embedding offers great modularity, extensibility and flexibility.
882 However, user-defined data types are awkward to handle because the built-in operations on them---construction, deconstruction and constructor tests---are not inherited from the host language.
883 We showed how to create a \gls{TH} function that will splice the required class definitions and view instances.
884 The code dataset also contains an implementation for defining field selectors and provides an implementation for a compiler (see \cref{chp:research_data_management}).
885 Furthermore, by writing a custom quasiquoter, pattern matches in natural syntax can be automatically converted to the internal representation of the \gls{DSL}, thus removing the syntax burden of the facilities.
886 The use of a custom quasiquoter does require the \gls{DSL} programmer to write a parser for their \gls{DSL}, i.e.\ the parser is not inherited from the host language as is often the case in an embedded \gls{DSL}.
887 However, by making use of modern parser combinator libraries, this overhead is limited and errors are already caught at compilation.
888
889 \subsection{Future work}
890 For future work, it would be interesting to see how generating boilerplate for user-defined data types translates from shallow embedding to deep embedding.
891 In deep embedding, the language constructs are expressed as data types in the host language.
892 Adding new constructs, e.g.\ constructors, deconstructors, and constructor tests, for the user-defined data type therefore requires extending the data type.
893 Techniques such as data types \`a la carte~\citep{swierstra_data_2008} and open data types~\citep{loh_open_2006} show that it is possible to extend data types orthogonally but whether metaprogramming can still readily be used is something that needs to be researched.
894 It may also be possible to implemented (parts) of the boilerplate generation using \gls{TTH} (see \cref{ssec_fcd:typed_template_haskell}) to achieve more confidence in the type correctness of the implementation.
895
896 Another venue of research is to try to find the limits of this technique regarding richer data type definitions.
897 It would be interesting to see whether it is possible to apply the technique on data types with existentially quantified type variables or full-fledged generalised \glspl{ADT}~\citep{hinze_fun_2003}.
898 It is not possible to straightforwardly lift the deconstructors to type classes because existentially quantified type variables will escape.
899 Rank-2 polymorphism offers tools to define the types in such a way that this is not the case anymore.
900 However, implementing compiling views on the \gls{DSL} is complicated because it would require inventing values of an existentially quantified type variable to satisfy the type system which is difficult.
901
902 Finally, having to write a parser for the \gls{DSL} is extra work.
903 Future research could determine whether it is possible to generate this using \gls{TH} as well.
904
905 \input{subfilepostamble}
906 \end{document}