bd3b59a8b9ad3ae62eb054cccf9ebc6869445a3e
[phd-thesis.git] / dsl / class_deep_embedding.tex
1 \documentclass[../thesis.tex]{subfiles}
2
3 \begin{document}
4 \ifSubfilesClassLoaded{
5 \pagenumbering{arabic}
6 }{}
7
8 \chapter{Deep embedding with class}%
9 \label{chp:classy_deep_embedding}
10
11 \begin{chapterabstract}
12 The two flavours of DSL embedding are shallow and deep embedding.
13 In functional languages, shallow embedding models the language constructs as functions in which the semantics are embedded.
14 Adding semantics is therefore cumbersome while adding constructs is a breeze.
15 Upgrading the functions to type classes lifts this limitation to a certain extent.
16
17 Deeply embedded languages represent their language constructs as data and the semantics are functions on it.
18 As a result, the language constructs are embedded in the semantics, hence adding new language constructs is laborious where adding semantics is trouble free.
19
20 This paper shows that by abstracting the semantics functions in deep embedding to type classes, it is possible to easily add language constructs as well.
21 So-called classy deep embedding results in DSLs that are extensible both in language constructs and in semantics while maintaining a concrete abstract syntax tree.
22 Additionally, little type-level trickery or complicated boilerplate code is required to achieve this.
23 \end{chapterabstract}
24
25 \section{Introduction}
26 The two flavours of DSL embedding are deep and shallow embedding~\citep{boulton_experience_1992}.
27 In functional programming languages, shallow embedding models language constructs as functions in the host language.
28 As a result, adding new language constructs---extra functions---is easy.
29 However, the semantics of the language is embedded in these functions, making it troublesome to add semantics since it requires updating all existing language constructs.
30
31 On the other hand, deep embedding models language constructs as data in the host language.
32 The semantics of the language are represented by functions over the data.
33 Consequently, adding new semantics, i.e.\ novel functions, is straightforward.
34 It can be stated that the language constructs are embedded in the functions that form a semantics.
35 If one wants to add a language construct, all semantics functions must be revisited and revised to avoid ending up with partial functions.
36
37 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}:
38
39 \begin{quote}
40 The \emph{expression problem} is a new name for an old problem.
41 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).
42 \end{quote}
43
44 In shallow embedding, abstracting the functions to type classes disentangles the language constructs from the semantics, allowing extension both ways.
45 This technique is dubbed tagless-final embedding~\citep{carette_finally_2009}, nonetheless it is no silver bullet.
46 Some semantics that require an intensional analysis of the syntax tree, such as transformation and optimisations, are difficult to implement in shallow embedding due to the lack of an explicit data structure representing the abstract syntax tree.
47 The semantics of the DSL have to be combined and must hold some kind of state or context, so that structural information is not lost~\citep{kiselyov_typed_2012}.
48
49 \subsection{Research contribution}
50 This paper shows how to apply the technique observed in tagless-final embedding to deep embedding.
51 The presented basic technique, christened \emph{classy deep embedding}, does not require advanced type system extensions to be used.
52 However, it is suitable for type system extensions such as generalised algebraic data types.
53 While this paper is written as a literate
54 Haskell~\citep{peyton_jones_haskell_2003} program using some minor extensions provided by GHC~\citep{ghc_team_ghc_2021}, the idea is applicable to other languages as well\footnotemark{}.
55 \footnotetext{Lubbers, M. (2021): Literate Haskell/lhs2\TeX{} source code of the paper ``Deep Embedding
56 with Class'': TFP 2022.\ DANS.\ \url{https://doi.org/10.5281/zenodo.5081386}.}
57
58 \section{Deep embedding}
59 Pick a DSL, any DSL, pick the language of literal integers and addition.
60 In deep embedding, terms in the language are represented by data in the host language.
61 Hence, defining the constructs is as simple as creating the following algebraic data type\footnote{All data types and functions are subscripted to indicate the evolution.}.
62
63 \begin{lstHaskellLhstex}
64 data Expr_0 = Lit_0 Int
65 | Add_0 Expr_0 Expr_0
66 \end{lstHaskellLhstex}
67
68 Semantics are defined as functions on the \haskelllhstexinline{Expr_0} data type.
69 For example, a function transforming the term to an integer---an evaluator---is implemented as follows.
70
71 \begin{lstHaskellLhstex}
72 eval_0 :: Expr_0 -> Int
73 eval_0 (Lit_0 e) = e
74 eval_0 (Add_0 e1 e2) = eval_0 e1 + eval_0 e2
75 \end{lstHaskellLhstex}
76
77 Adding semantics---e.g.\ a printer---just means adding another function while the existing functions remain untouched.
78 I.e.\ the key property of deep embedding.
79 The following function, transforming the \haskelllhstexinline{Expr_0} data type to a string, defines a simple printer for our language.
80
81 \begin{lstHaskellLhstex}
82 print_0 :: Expr_0 -> String
83 print_0 (Lit_0 v) = show v
84 print_0 (Add_0 e1 e2) = "(" ++ print_0 e1 ++ "-" ++ print_0 e2 ++ ")"
85 \end{lstHaskellLhstex}
86
87 While the language is concise and elegant, it is not very expressive.
88 Traditionally, extending the language is achieved by adding a case to the \haskelllhstexinline{Expr_0} data type.
89 So, adding subtraction to the language results in the following revised data type.
90
91 \begin{lstHaskellLhstex}
92 data Expr_0 = Lit_0 Int
93 | Add_0 Expr_0 Expr_0
94 | Sub_0 Expr_0 Expr_0
95 \end{lstHaskellLhstex}
96
97 Extending the DSL with language constructs exposes the Achilles' heel of deep embedding.
98 Adding a case to the data type means that all semantics functions have become partial and need to be updated to be able to handle this new case.
99 This does not seem like an insurmountable problem, but it does pose a problem if either the functions or the data type itself are written by others or are contained in a closed library.
100
101 \section{Shallow embedding}
102 Conversely, let us see how this would be done in shallow embedding.
103 First, the data type is represented by functions in the host language with embedded semantics.
104 Therefore, the evaluators for literals and addition both become a function in the host language as follows.
105
106 \begin{lstHaskellLhstex}
107 type Sem_s = Int
108
109 lit_s :: Int -> Sem_s
110 lit_s i = i
111
112 add_s :: Sem_s -> Sem_s -> Sem_s
113 add_s e1 e2 = e1 + e2
114 \end{lstHaskellLhstex}
115
116 Adding constructions to the language is done by adding functions.
117 Hence, the following function adds subtraction to our language.
118
119 \begin{lstHaskellLhstex}
120 sub_s :: Sem_s -> Sem_s -> Sem_s
121 sub_s e1 e2 = e1 - e2
122 \end{lstHaskellLhstex}
123
124 Adding semantics on the other hand---e.g.\ a printer---is not that simple because the semantics are part of the functions representing the language constructs.
125 One way to add semantics is to change all functions to execute both semantics at the same time.
126 In our case this means changing the type of \haskelllhstexinline{Sem_s} to be \haskelllhstexinline{(Int, String)} so that all functions operate on a tuple containing the result of the evaluator and the printed representation at the same time. %chktex 36
127 Alternatively, a single semantics can be defined that represents a fold over the language constructs~\citep{gibbons_folding_2014}, delaying the selection of semantics to the moment the fold is applied.
128
129 \subsection{Tagless-final embedding}
130 Tagless-final embedding overcomes the limitations of standard shallow embedding.
131 To upgrade to this embedding technique, the language constructs are changed from functions to type classes.
132 For our language this results in the following type class definition.
133
134 \begin{lstHaskellLhstex}
135 class Expr_t s where
136 lit_t :: Int -> s
137 add_t :: s -> s -> s
138 \end{lstHaskellLhstex}
139
140 Semantics become data types\footnotemark{} implementing these type classes, resulting in the following instance for the evaluator.
141 \footnotetext{%
142 In this case \haskelllhstexinline{newtype}s are used instead of regular \haskelllhstexinline{data} declarations.
143 A \haskelllhstexinline{newtype} is a special data type with a single constructor containing a single value only to which it is isomorphic.
144 It allows the programmer to define separate class instances that the instances of the isomorphic type without any overhead.
145 During compilation the constructor is completely removed~\citep[Sec.~4.2.3]{peyton_jones_haskell_2003}.
146 }
147
148 \begin{lstHaskellLhstex}
149 newtype Eval_t = E_t Int
150
151 instance Expr_t Eval_t where
152 lit_t v = E_t v
153 add_t (E_t e1) (E_t e2) = E_t (e1 + e2)
154 \end{lstHaskellLhstex}
155
156 Adding constructs---e.g.\ subtraction---just results in an extra type class and corresponding instances.
157
158 \begin{lstHaskellLhstex}
159 class Sub_t s where
160 sub_t :: s -> s -> s
161
162 instance Sub_t Eval_t where
163 sub_t (E_t e1) (E_t e2) = E_t (e1 - e2)
164 \end{lstHaskellLhstex}
165
166 Finally, adding semantics such as a printer over the language is achieved by providing a data type representing the semantics accompanied by instances for the language constructs.
167
168 \begin{lstHaskellLhstex}
169 newtype Printer_t = P_t String
170
171 instance Expr_t Printer_t where
172 lit_t i = P_t (show i)
173 add_t (P_t e1) (P_t e2) = P_t ("(" ++ e1 ++ "+" ++ e2 ++ ")")
174
175 instance Sub_t Printer_t where
176 sub_t (P_t e1) (P_t e2) = P_t ("(" ++ e1 ++ "-" ++ e2 ++ ")")
177 \end{lstHaskellLhstex}
178
179 \section{Lifting the backends}%
180 Let us rethink the deeply embedded DSL design.
181 Remember that in shallow embedding, the semantics are embedded in the language construct functions.
182 Obtaining extensibility both in constructs and semantics was accomplished by abstracting the semantics functions to type classes, making the constructs overloaded in the semantics.
183 In deep embedding, the constructs are embedded in the semantics functions instead.
184 So, let us apply the same technique, i.e.\ make the semantics overloaded in the language constructs by abstracting the semantics functions to type classes.
185 The same effect may be achieved when using similar techniques such as explicit dictionary passing or ML style modules.
186 In our language this results in the following type class.
187
188 \begin{lstHaskellLhstex}
189 class Eval_1 v where
190 eval_1 :: v -> Int
191
192 data Expr_1 = Lit_1 Int
193 | Add_1 Expr_1 Expr_1
194 \end{lstHaskellLhstex}
195
196 Implementing the semantics type class instances for the \haskelllhstexinline{Expr_1} data type is an elementary exercise.
197 By a copy-paste and some modifications, we come to the following implementation.
198
199 \begin{lstHaskellLhstex}
200 instance Eval_1 Expr_1 where
201 eval_1 (Lit_1 v) = v
202 eval_1 (Add_1 e1 e2) = eval_1 e1 + eval_1 e2
203 \end{lstHaskellLhstex}
204
205 Subtraction can now be defined in a separate data type, leaving the original data type intact.
206 Instances for the additional semantics can now be implemented separately as instances of the type classes.
207
208 \begin{lstHaskellLhstex}
209 data Sub_1 = Sub_1 Expr_1 Expr_1
210
211 instance Eval_1 Sub_1 where
212 eval_1 (Sub_1 e1 e2) = eval_1 e1 - eval_1 e2
213 \end{lstHaskellLhstex}
214
215 \section{Existential data types}%
216
217 The astute reader might have noticed that we have dissociated ourselves from the original data type.
218 It is only possible to create an expression with a subtraction on the top level.
219 The recursive knot is left untied and as a result, \haskelllhstexinline{Sub_1} can never be reached from an \haskelllhstexinline{Expr_1}.
220
221 Luckily, we can reconnect them by adding a special constructor to the \haskelllhstexinline{Expr_1} data type for housing extensions.
222 It contains an existentially quantified~\citep{mitchell_abstract_1988} type with type class constraints~\citep{laufer_combining_1994,laufer_type_1996} for all semantics type classes~\citep[Chp.~6.4.6]{ghc_team_ghc_2021} to allow it to house not just subtraction but any future extension.
223
224 \begin{lstHaskellLhstex}
225 data Expr_2 = Lit_2 Int
226 | Add_2 Expr_2 Expr_2
227 | forall x. Eval_2 x => Ext_2 x
228 \end{lstHaskellLhstex}
229
230 The implementation of the extension case in the semantics type classes is in most cases just a matter of calling the function for the argument as can be seen in the semantics instances shown below.
231
232 \begin{lstHaskellLhstex}
233 instance Eval_2 Expr_2 where
234 eval_2 (Lit_2 v) = v
235 eval_2 (Add_2 e1 e2) = eval_2 e1 + eval_2 e2
236 eval_2 (Ext_2 x) = eval_2 x
237 \end{lstHaskellLhstex}
238
239 Adding language construct extensions in different data types does mean that an extra \haskelllhstexinline{Ext_2} tag is introduced when using the extension.
240 This burden can be relieved by creating a smart constructor for it that automatically wraps the extension with the \haskelllhstexinline{Ext_2} constructor so that it is of the type of the main data type.
241
242 \begin{lstHaskellLhstex}
243 sub_2 :: Expr_2 -> Expr_2 -> Expr_2
244 sub_2 e1 e2 = Ext_2 (Sub_2 e1 e2)
245 \end{lstHaskellLhstex}
246
247 In our example this means that the programmer can write\footnotemark{}:
248 \footnotetext{%
249 Backticks are used to use functions or constructors in an infix fashion~\citep[Sec.~4.3.3]{peyton_jones_haskell_2003}.
250 }
251 \begin{lstHaskellLhstex}
252 e2 :: Expr_2
253 e2 = Lit_2 42 `sub_2` Lit_2 1
254 \end{lstHaskellLhstex}
255 instead of having to write
256 \begin{lstHaskellLhstex}
257 e2p :: Expr_2
258 e2p = Ext_2 (Lit_2 42 `Sub_2` Lit_2 1)
259 \end{lstHaskellLhstex}
260
261 \subsection{Unbraiding the semantics from the data}
262 This approach does reveal a minor problem.
263 Namely, that all semantics type classes are braided into our datatypes via the \haskelllhstexinline{Ext_2} constructor.
264 Say if we add the printer again, the \haskelllhstexinline{Ext_2} constructor has to be modified to contain the printer type class constraint as well\footnote{Resulting in the following constructor: \haskelllhstexinline{forall x.(Eval_2 x, Print_2 x) => Ext_2 x}.}. %chktex 36
265 Thus, if we add semantics, the main data type's type class constraints in the \haskelllhstexinline{Ext_2} constructor need to be updated.
266 To avoid this, the type classes can be bundled in a type class alias or type class collection as follows.
267
268 \begin{lstHaskellLhstex}
269 class (Eval_2 x, Print_2 x) => Semantics_2 x
270
271 data Expr_2 = Lit_2 Int
272 | Add_2 Expr_2 Expr_2
273 | forall x. Semantics_2 x => Ext_2 x
274 \end{lstHaskellLhstex}
275
276 The class alias removes the need for the programmer to visit the main data type when adding additional semantics.
277 Unfortunately, the compiler does need to visit the main data type again.
278 Some may argue that adding semantics happens less frequently than adding language constructs but in reality it means that we have to concede that the language is not as easily extensible in semantics as in language constructs.
279 More exotic type system extensions such as constraint kinds~\citep{bolingbroke_constraint_2011,yorgey_giving_2012} can untangle the semantics from the data types by making the data types parametrised by the particular semantics.
280 However, by adding some boilerplate, even without this extension, the language constructs can be parametrised by the semantics by putting the semantics functions in a data type.
281 First the data types for the language constructs are parametrised by the type variable \haskelllhstexinline{d} as follows.
282
283 \begin{lstHaskellLhstex}
284 data Expr_3 d = Lit_3 Int
285 | Add_3 (Expr_3 d) (Expr_3 d)
286 | forall x. Ext_3 (d x) x
287
288 data Sub_3 d = Sub_3 (Expr_3 d) (Expr_3 d)
289 \end{lstHaskellLhstex}
290
291 The \haskelllhstexinline{d} type variable is inhabited by an explicit dictionary for the semantics, i.e.\ a witness to the class instance.
292 Therefore, for all semantics type classes, a data type is made that contains the semantics function for the given semantics.
293 This means that for \haskelllhstexinline{Eval_3}, a dictionary with the function \haskelllhstexinline{EvalDict_3} is defined, a type class \haskelllhstexinline{HasEval_3} for retrieving the function from the dictionary and an instance for \haskelllhstexinline{HasEval_3} for \haskelllhstexinline{EvalDict_3}.
294
295 \begin{lstHaskellLhstex}
296 newtype EvalDict_3 v = EvalDict_3 (v -> Int)
297
298 class HasEval_3 d where
299 getEval_3 :: d v -> v -> Int
300
301 instance HasEval_3 EvalDict_3 where
302 getEval_3 (EvalDict_3 e) = e
303 \end{lstHaskellLhstex}
304
305 The instances for the type classes change as well according to the change in the datatype.
306 Given that there is a \haskelllhstexinline{HasEval_3} instance for the witness type \haskelllhstexinline{d}, we can provide an implementation of \haskelllhstexinline{Eval_3} for \haskelllhstexinline{Expr_3 d}.
307
308 \begin{lstHaskellLhstex}
309 instance HasEval_3 d => Eval_3 (Expr_3 d) where
310 eval_3 (Lit_3 v) = v
311 eval_3 (Add_3 e1 e2) = eval_3 e1 + eval_3 e2
312 eval_3 (Ext_3 d x) = getEval_3 d x
313
314 instance HasEval_3 d => Eval_3 (Sub_3 d) where
315 eval_3 (Sub_3 e1 e2) = eval_3 e1 - eval_3 e2
316 \end{lstHaskellLhstex}
317
318 Because the \haskelllhstexinline{Ext_3} constructor from \haskelllhstexinline{Expr_3} now contains a value of type \haskelllhstexinline{d}, the smart constructor for \haskelllhstexinline{Sub_3} must somehow come up with this value.
319 To achieve this, a type class is introduced that allows the generation of such a dictionary.
320
321 \begin{lstHaskellLhstex}
322 class GDict a where
323 gdict :: a
324 \end{lstHaskellLhstex}
325
326 This type class has individual instances for all semantics dictionaries, linking the class instance to the witness value.
327 I.e.\ if there is a type class instance known, a witness value can be conjured using the \haskelllhstexinline{gdict} function.
328
329 \begin{lstHaskellLhstex}
330 instance Eval_3 v => GDict (EvalDict_3 v) where
331 gdict = EvalDict_3 eval_3
332 \end{lstHaskellLhstex}
333
334 With these instances, the semantics function can be retrieved from the \haskelllhstexinline{Ext_3} constructor and in the smart constructors they can be generated as follows:
335
336 \begin{lstHaskellLhstex}
337 sub_3 :: GDict (d (Sub_3 d)) => Expr_3 d -> Expr_3 d -> Expr_3 d
338 sub_3 e1 e2 = Ext_3 gdict (Sub_3 e1 e2)
339 \end{lstHaskellLhstex}
340
341 Finally, we reached the end goal, orthogonal extension of both language constructs as shown by adding subtraction to the language and in language semantics.
342 Adding the printer can now be done without touching the original code as follows.
343 First the printer type class, dictionaries and instances for \haskelllhstexinline{GDict} are defined.
344
345 \begin{lstHaskellLhstex}
346 class Print_3 v where
347 print_3 :: v -> String
348
349 newtype PrintDict_3 v = PrintDict_3 (v -> String)
350
351 class HasPrint_3 d where
352 getPrint_3 :: d v -> v -> String
353
354 instance HasPrint_3 PrintDict_3 where
355 getPrint_3 (PrintDict_3 e) = e
356
357 instance Print_3 v => GDict (PrintDict_3 v) where
358 gdict = PrintDict_3 print_3
359 \end{lstHaskellLhstex}
360
361 Then the instances for \haskelllhstexinline{Print_3} of all the language constructs can be defined.
362
363 \begin{lstHaskellLhstex}
364 instance HasPrint_3 d => Print_3 (Expr_3 d) where
365 print_3 (Lit_3 v) = show v
366 print_3 (Add_3 e1 e2) = "(" ++ print_3 e1 ++ "+" ++ print_3 e2 ++ ")"
367 print_3 (Ext_3 d x) = getPrint_3 d x
368 instance HasPrint_3 d => Print_3 (Sub_3 d) where
369 print_3 (Sub_3 e1 e2) = "(" ++ print_3 e1 ++ "-" ++ print_3 e2 ++ ")"
370 \end{lstHaskellLhstex}
371
372 \section{Transformation semantics}
373 Most semantics convert a term to some final representation and can be expressed just by functions on the cases.
374 However, the implementation of semantics such as transformation or optimisation may benefit from a so-called intentional analysis of the abstract syntax tree.
375 In shallow embedding, the implementation for these types of semantics is difficult because there is no tangible abstract syntax tree.
376 In off-the-shelf deep embedding this is effortless since the function can pattern match on the constructor or structures of constructors.
377
378 To demonstrate intensional analyses in classy deep embedding we write an optimizer that removes addition and subtraction by zero.
379 In classy deep embedding, adding new semantics means first adding a new type class housing the function including the machinery for the extension constructor.
380
381 \begin{lstHaskellLhstex}
382 class Opt_3 v where
383 opt_3 :: v -> v
384
385 newtype OptDict_3 v = OptDict_3 (v -> v)
386
387 class HasOpt_3 d where
388 getOpt_3 :: d v -> v -> v
389
390 instance HasOpt_3 OptDict_3 where
391 getOpt_3 (OptDict_3 e) = e
392
393 instance Opt_3 v => GDict (OptDict_3 v) where
394 gdict = OptDict_3 opt_3
395 \end{lstHaskellLhstex}
396
397 The implementation of the optimizer for the \haskelllhstexinline{Expr_3} data type is no complicated task.
398 The only interesting bit occurs in the \haskelllhstexinline{Add_3} constructor, where we pattern match on the optimised children to determine whether an addition with zero is performed.
399 If this is the case, the addition is removed.
400
401 \begin{lstHaskellLhstex}
402 instance HasOpt_3 d => Opt_3 (Expr_3 d) where
403 opt_3 (Lit_3 v) = Lit_3 v
404 opt_3 (Add_3 e1 e2) = case (opt_3 e1, opt_3 e2) of
405 (Lit_3 0, e2p ) -> e2p
406 (e1p, Lit_3 0) -> e1p
407 (e1p, e2p ) -> Add_3 e1p e2p
408 opt_3 (Ext_3 d x) = Ext_3 d (getOpt_3 d x)
409 \end{lstHaskellLhstex}
410
411 Replicating this for the \haskelllhstexinline{Opt_3} instance of \haskelllhstexinline{Sub_3} seems a clear-cut task at first glance.
412
413 \begin{lstHaskellLhstex}
414 instance HasOpt_3 d => Opt_3 (Sub_3 d) where
415 opt_3 (Sub_3 e1 e2) = case (opt_3 e1, opt_3 e2) of
416 (e1p, Lit_3 0) -> e1p
417 (e1p, e2p ) -> Sub_3 e1p e2p
418 \end{lstHaskellLhstex}
419
420 Unsurprisingly, this code is rejected by the compiler.
421 When a literal zero is matched as the right-hand side of a subtraction, the left-hand side of type \haskelllhstexinline{Expr_3} is returned.
422 However, the type signature of the function dictates that it should be of type \haskelllhstexinline{Sub_3}.
423 To overcome this problem we add a convolution constructor.
424
425 \subsection{Convolution}
426 Adding a loopback case or convolution constructor to \haskelllhstexinline{Sub_3} allows the removal of the \haskelllhstexinline{Sub_3} constructor while remaining the \haskelllhstexinline{Sub_3} type.
427 It should be noted that a loopback case is \emph{only} required if the transformation actually removes tags.
428 This changes the \haskelllhstexinline{Sub_3} data type as follows.
429
430 \begin{lstHaskellLhstex}
431 data Sub_4 d = Sub_4 (Expr_4 d) (Expr_4 d)
432 | SubLoop_4 (Expr_4 d)
433
434 instance HasEval_4 d => Eval_4 (Sub_4 d) where
435 eval_4 (Sub_4 e1 e2) = eval_4 e1 - eval_4 e2
436 eval_4 (SubLoop_4 e1) = eval_4 e1
437 \end{lstHaskellLhstex}
438
439 With this loopback case in the toolbox, the following \haskelllhstexinline{Sub} instance optimises away subtraction with zero literals.
440
441 \begin{lstHaskellLhstex}
442 instance HasOpt_4 d => Opt_4 (Sub_4 d) where
443 opt_4 (Sub_4 e1 e2) = case (opt_4 e1, opt_4 e2) of
444 (e1p, Lit_4 0) -> SubLoop_4 e1p
445 (e1p, e2p ) -> Sub_4 e1p e2p
446 opt_4 (SubLoop_4 e) = SubLoop_4 (opt_4 e)
447 \end{lstHaskellLhstex}
448
449 \subsection{Pattern matching}
450 Pattern matching within datatypes and from an extension to the main data type works out of the box.
451 Cross-extensional pattern matching on the other hand---matching on a particular extension---is something that requires a bit of extra care.
452 Take for example negation propagation and double negation elimination.
453 Pattern matching on values with an existential type is not possible without leveraging dynamic typing~\citep{abadi_dynamic_1991,baars_typing_2002}.
454 To enable dynamic typing support, the \haskelllhstexinline{Typeable} type class as provided by \haskelllhstexinline{Data.Dynamic}~\citep{ghc_team_datadynamic_2021} is added to the list of constraints in all places where we need to pattern match across extensions.
455 As a result, the \haskelllhstexinline{Typeable} type class constraints are added to the quantified type variable \haskelllhstexinline{x} of the \haskelllhstexinline{Ext_4} constructor and to \haskelllhstexinline{d}s in the smart constructors.
456
457 \begin{lstHaskellLhstex}
458 data Expr_4 d = Lit_4 Int
459 | Add_4 (Expr_4 d) (Expr_4 d)
460 | forall x. Typeable x => Ext_4 (d x) x
461 \end{lstHaskellLhstex}
462
463 First let us add negation to the language by defining a datatype representing it.
464 Negation elimination requires the removal of negation constructors, so a convolution constructor is defined as well.
465
466 \begin{lstHaskellLhstex}
467 data Neg_4 d = Neg_4 (Expr_4 d)
468 | NegLoop_4 (Expr_4 d)
469
470 neg_4 :: (Typeable d, GDict (d (Neg_4 d))) => Expr_4 d -> Expr_4 d
471 neg_4 e = Ext_4 gdict (Neg_4 e)
472 \end{lstHaskellLhstex}
473
474 The evaluation and printer instances for the \haskelllhstexinline{Neg_4} datatype are defined as follows.
475
476 \begin{lstHaskellLhstex}
477 instance HasEval_4 d => Eval_4 (Neg_4 d) where
478 eval_4 (Neg_4 e) = negate (eval_4 e)
479 eval_4 (NegLoop_4 e) = eval_4 e
480
481 instance HasPrint_4 d => Print_4 (Neg_4 d) where
482 print_4 (Neg_4 e) = "(~" ++ print_4 e ++ ")"
483 print_4 (NegLoop_4 e) = print_4 e
484 \end{lstHaskellLhstex}
485
486 The \haskelllhstexinline{Opt_4} instance contains the interesting bit.
487 If the sub expression of a negation is an addition, negation is propagated downwards.
488 If the sub expression is again a negation, something that can only be found out by a dynamic pattern match, it is replaced by a \haskelllhstexinline{NegLoop_4} constructor.
489
490 \begin{lstHaskellLhstex}
491 instance (Typeable d, GDict (d (Neg_4 d)), HasOpt_4 d) => Opt_4 (Neg_4 d) where
492 opt_4 (Neg_4 (Add_4 e1 e2))
493 = NegLoop_4 (Add_4 (opt_4 (neg_4 e1)) (opt_4 (neg_4 e2)))
494 opt_4 (Neg_4 (Ext_4 d x))
495 = case fromDynamic (toDyn (getOpt_4 d x)) of
496 Just (Neg_4 e) -> NegLoop_4 e
497 _ -> Neg_4 (Ext_4 d (getOpt_4 d x))
498 opt_4 (Neg_4 e) = Neg_4 (opt_4 e)
499 opt_4 (NegLoop_4 e) = NegLoop_4 (opt_4 e)
500 \end{lstHaskellLhstex}
501
502 Loopback cases do make cross-extensional pattern matching less modular in general.
503 For example, \haskelllhstexinline{Ext_4 d (SubLoop_4 (Lit_4 0))} is equivalent to \haskelllhstexinline{Lit_4 0} in the optimisation semantics and would require an extra pattern match.
504 Fortunately, this problem can be mitigated---if required---by just introducing an additional optimisation semantics that removes loopback cases.
505 Luckily, one does not need to resort to these arguably blunt matters often.
506 Dependent language functionality often does not need to span extensions, i.e.\ it is possible to group them in the same data type.
507
508 \subsection{Chaining semantics}
509 Now that the data types are parametrised by the semantics a final problem needs to be overcome.
510 The data type is parametrised by the semantics, thus, using multiple semantics, such as evaluation after optimising is not straightforwardly possible.
511 Luckily, a solution is readily at hand: introduce an ad-hoc combination semantics.
512
513 \begin{lstHaskellLhstex}
514 data OptPrintDict_4 v = OPD_4 (OptDict_4 v) (PrintDict_4 v)
515
516 instance HasOpt_4 OptPrintDict_4 where
517 getOpt_4 (OPD_4 v _) = getOpt_4 v
518 instance HasPrint_4 OptPrintDict_4 where
519 getPrint_4 (OPD_4 _ v) = getPrint_4 v
520
521 instance (Opt_4 v, Print_4 v) => GDict (OptPrintDict_4 v) where
522 gdict = OPD_4 gdict gdict
523 \end{lstHaskellLhstex}
524
525 And this allows us to write \haskelllhstexinline{print_4 (opt_4 e1)} resulting in \verb|"((~42)+(~38))"| when \haskelllhstexinline{e1} represents $(\sim(42+38))-0$ and is thus defined as follows.
526
527 \begin{lstHaskellLhstex}
528 e1 :: Expr_4 OptPrintDict_4
529 e1 = neg_4 (Lit_4 42 `Add_4` Lit_4 38) `sub_4` Lit_4 0
530 \end{lstHaskellLhstex}
531
532 When using classy deep embedding to the fullest, the ability of the compiler to infer very general types expires.
533 As a consequence, defining reusable expressions that are overloaded in their semantics requires quite some type class constraints that cannot be inferred by the compiler (yet) if they use many extensions.
534 Solving this remains future work.
535 For example, the expression $\sim(42-38)+1$ has to be defined as:
536
537 \begin{lstHaskellLhstex}
538 e3 :: (Typeable d, GDict (d (Neg_4 d)), GDict (d (Sub_4 d))) => Expr_4 d
539 e3 = neg_4 (Lit_4 42 `sub_4` Lit_4 38) `Add_4` Lit_4 1
540 \end{lstHaskellLhstex}
541
542 \section{Chaining (reprise)}\label{sec:classy_reprise}
543 \todo{\ldots}
544
545 \section{Generalised algebraic data types}%
546 Generalised algebraic data types (GADTs) are enriched data types that allow the type instantiation of the constructor to be explicitly defined~\citep{cheney_first-class_2003,hinze_fun_2003}.
547 Leveraging GADTs, deeply embedded DSLs can be made statically type safe even when different value types are supported.
548 Even when GADTs are not supported natively in the language, they can be simulated using embedding-projection pairs or equivalence types~\citep[Sec.~2.2]{cheney_lightweight_2002}.
549 Where some solutions to the expression problem do not easily generalise to GADTs (see \cref{sec:cde:related}), classy deep embedding does.
550 Generalising the data structure of our DSL is fairly straightforward and to spice things up a bit, we add an equality and boolean not language construct.
551 To make the existing DSL constructs more general, we relax the types of those constructors.
552 For example, operations on integers now work on all numerals instead.
553 Moreover, the \haskelllhstexinline{Lit_g} constructor can be used to lift values of any type to the DSL domain as long as they have a \haskelllhstexinline{Show} instance, required for the printer.
554 Since some optimisations on \haskelllhstexinline{Not_g} remove constructors and therefore use cross-extensional pattern matches, \haskelllhstexinline{Typeable} constraints are added to \haskelllhstexinline{a}.
555 Furthermore, because the optimisations for \haskelllhstexinline{Add_g} and \haskelllhstexinline{Sub_g} are now more general, they do not only work for \haskelllhstexinline{Int}s but for any type with a \haskelllhstexinline{Num} instance, the \haskelllhstexinline{Eq} constraint is added to these constructors as well.
556 Finally, not to repeat ourselves too much, we only show the parts that substantially changed.
557 The omitted definitions and implementation can be found in \cref{sec:cde:appendix}.
558
559 \begin{lstHaskellLhstex}
560 data Expr_g d a where
561 Lit_g :: Show a => a -> Expr_g d a
562 Add_g :: (Eq a, Num a) => Expr_g d a -> Expr_g d a -> Expr_g d a
563 Ext_g :: Typeable x => d x -> x a -> Expr_g d a
564 data Neg_g d a where
565 Neg_g :: (Typeable a, Num a) => Expr_g d a -> Neg_g d a
566 NegLoop_g :: Expr_g d a -> Neg_g d a
567 data Not_g d a where
568 Not_g :: Expr_g d Bool -> Not_g d Bool
569 NotLoop_g :: Expr_g d a -> Not_g d a
570 \end{lstHaskellLhstex}
571
572 The smart constructors for the language extensions inherit the class constraints of their data types and include a \haskelllhstexinline{Typeable} constraint on the \haskelllhstexinline{d} type variable for it to be usable in the \haskelllhstexinline{Ext_g} constructor as can be seen in the smart constructor for \haskelllhstexinline{Neg_g}:
573
574 \begin{lstHaskellLhstex}
575 neg_g :: (Typeable d, GDict (d (Neg_g d)), Typeable a, Num a) =>
576 Expr_g d a -> Expr_g d a
577 neg_g e = Ext_g gdict (Neg_g e)
578
579 not_g :: (Typeable d, GDict (d (Not_g d))) =>
580 Expr_g d Bool -> Expr_g d Bool
581 not_g e = Ext_g gdict (Not_g e)
582 \end{lstHaskellLhstex}
583
584 Upgrading the semantics type classes to support GADTs is done by an easy textual search and replace.
585 All occurrences of \haskelllhstexinline{v} are now parametrised by type variable \haskelllhstexinline{a}:
586
587 \begin{lstHaskellLhstex}
588 class Eval_g v where
589 eval_g :: v a -> a
590 class Print_g v where
591 print_g :: v a -> String
592 class Opt_g v where
593 opt_g :: v a -> v a
594 \end{lstHaskellLhstex}
595
596 Now that the shape of the type classes has changed, the dictionary data types and the type classes need to be adapted as well.
597 The introduced type variable \haskelllhstexinline{a} is not an argument to the type class, so it should not be an argument to the dictionary data type.
598 To represent this type class function, a rank-2 polymorphic function is needed~\citep[Chp.~6.4.15]{ghc_team_ghc_2021}\citep{odersky_putting_1996}.
599 Concretely, for the evaluatior this results in the following definitions:
600
601 \begin{lstHaskellLhstex}
602 newtype EvalDict_g v = EvalDict_g (forall a. v a -> a)
603 class HasEval_g d where
604 getEval_g :: d v -> v a -> a
605 instance HasEval_g EvalDict_g where
606 getEval_g (EvalDict_g e) = e
607 \end{lstHaskellLhstex}
608
609 The \haskelllhstexinline{GDict} type class is general enough, so the instances can remain the same.
610 The \haskelllhstexinline{Eval_g} instance of \haskelllhstexinline{GDict} looks as follows:
611
612 \begin{lstHaskellLhstex}
613 instance Eval_g v => GDict (EvalDict_g v) where
614 gdict = EvalDict_g eval_g
615 \end{lstHaskellLhstex}
616
617 Finally, the implementations for the instances can be ported without complication show using the optimisation instance of \haskelllhstexinline{Not_g}:
618
619 \begin{lstHaskellLhstex}
620 instance (Typeable d, GDict (d (Not_g d)), HasOpt_g d) => Opt_g (Not_g d) where
621 opt_g (Not_g (Ext_g d x))
622 = case fromDynamic (toDyn (getOpt_g d x)) :: Maybe (Not_g d Bool) of
623 Just (Not_g e) -> NotLoop_g e
624 _ -> Not_g (Ext_g d (getOpt_g d x))
625 opt_g (Not_g e) = Not_g (opt_g e)
626 opt_g (NotLoop_g e) = NotLoop_g (opt_g e)
627 \end{lstHaskellLhstex}
628
629 \section{Conclusion}%
630
631 Classy deep embedding is a novel organically grown embedding technique that alleviates deep embedding from the extensibility problem in most cases.
632
633 By abstracting the semantics functions to type classes they become overloaded in the language constructs.
634 Thus, making it possible to add new language constructs in a separate type.
635 These extensions are brought together in a special extension constructor residing in the main data type.
636 This extension case is overloaded by the language construct using a data type containing the class dictionary.
637 As a result, orthogonal extension is possible for language constructs and semantics using only little syntactic overhead or type annotations.
638 The basic technique only requires---well established through history and relatively standard---existential data types.
639 However, if needed, the technique generalises to GADTs as well, adding rank-2 types to the list of type system requirements as well.
640 Finally, the abstract syntax tree remains observable which makes it suitable for intensional analyses, albeit using occasional dynamic typing for truly cross-extensional transformations.
641
642 Defining reusable expressions overloaded in semantics or using multiple semantics on a single expression requires some boilerplate still, getting around this remains future work.
643
644 \section{Related work}%
645 \label{sec:cde:related}
646
647 Embedded DSL techniques in functional languages have been a topic of research for many years, thus we do not claim a complete overview of related work.
648
649 Clearly, classy deep embedding bears most similarity to the \emph{Datatypes \`a la Carte}~\citep{swierstra_data_2008}.
650 In Swierstra's approach, semantics are lifted to type classes similarly to classy deep embedding.
651 Each language construct is their own datatype parametrised by a type parameter.
652 This parameter contains some type level representation of language constructs that are in use.
653 In classy deep embedding, extensions do not have to be enumerated at the type level but are captured in the extension case.
654 Because all the constructs are expressed in the type system, nifty type system tricks need to be employed to convince the compiler that everything is type safe and the class constraints can be solved.
655 Furthermore, it requires some boilerplate code such as functor instances for the data types.
656 In return, pattern matching is easier and does not require dynamic typing.
657 Classy deep embedding only strains the programmer with writing the extension case for the main data type and the occasional loopback constructor.
658
659 L\"oh and Hinze proposed a language extension that allows open data types and open functions, i.e.\ functions and data types that can be extended with more cases later on~\citep{loh_open_2006}.
660 They hinted at the possibility of using type classes for open functions but had serious concerns that pattern matching would be crippled because constructors are becoming types, thus ultimately becoming impossible to type.
661 In contrast, this paper shows that pattern matching is easily attainable---albeit using dynamic types---and that the terms can be typed without complicated type system extensions.
662
663 A technique similar to classy deep embedding was proposed by Najd and Peyton~Jones to tackle a slightly different problem, namely that of reusing a data type for multiple purposes in a slightly different form~\citep{najd_trees_2017}.
664 For example to decorate the abstract syntax tree of a compiler differently for each phase of the compiler.
665 They propose to add an extension descriptor as a type variable to a data type and a type family that can be used to decorate constructors with extra information and add additional constructors to the data type using an extension constructor.
666 Classy deep embedding works similarly but uses existentially quantified type variables to describe possible extensions instead of type variables and type families.
667 In classy deep embedding, the extensions do not need to be encoded in the type system and less boilerplate is required.
668 Furthermore, pattern matching on extensions becomes a bit more complicated but in return it allows for multiple extensions to be added orthogonally and avoids the necessity for type system extensions.
669
670 Tagless-final embedding is the shallowly embedded counterpart of classy deep embedding and was invented for the same purpose; overcoming the issues with standard shallow embedding~\citep{carette_finally_2009}.
671 Classy deep embedding was organically grown from observing the evolution of tagless-final embedding.
672 The main difference between tagless-final embedding and classy deep embedding---and in general between shallow and deep embedding---is that intensional analyses of the abstract syntax tree is more difficult because there is no tangible abstract syntax tree data structure.
673 In classy deep embedding, it is possible to define transformations even across extensions.
674
675 Hybrid approaches between deep and shallow embedding exist as well.
676 For example, Svenningson et al.\ show that by expressing the deeply embedded language in a shallowly embedded core language, extensions can be made orthogonally as well~\citep{svenningsson_combining_2013}.
677 This paper differs from those approaches in the sense that it does not require a core language in which all extensions need to be expressible.
678
679 \section*{Acknowledgements}
680 This research is partly funded by the Royal Netherlands Navy.
681 Furthermore, I would like to thank Pieter and Rinus for the fruitful discussions, Ralf for inspiring me to write a functional pearl, and the anonymous reviewers for their valuable and honest comments.
682
683 \begin{subappendices}
684 \section{Data types and definitions}%
685 \label{sec:cde:appendix}
686 \begin{lstHaskellLhstex}[caption={Data type definitions.}]
687 data Sub_g d a where
688 Sub_g :: (Eq a, Num a) => Expr_g d a -> Expr_g d a -> Sub_g d a
689 SubLoop_g :: Expr_g d a -> Sub_g d a
690
691 data Eq_g d a where
692 Eq_g :: (Typeable a, Eq a) => Expr_g d a -> Expr_g d a -> Eq_g d Bool
693 EqLoop_g :: Expr_g d a -> Eq_g d a
694 \end{lstHaskellLhstex}
695
696 \begin{lstHaskellLhstex}[caption={Smart constructions.}]
697 sub_g :: (Typeable d, GDict (d (Sub_g d)), Eq a, Num a) =>
698 Expr_g d a -> Expr_g d a -> Expr_g d a
699 sub_g e1 e2 = Ext_g gdict (Sub_g e1 e2)
700
701 eq_g :: (Typeable d, GDict (d (Eq_g d)), Eq a, Typeable a) =>
702 Expr_g d a -> Expr_g d a -> Expr_g d Bool
703 eq_g e1 e2 = Ext_g gdict (Eq_g e1 e2)
704 \end{lstHaskellLhstex}
705
706 \begin{lstHaskellLhstex}[caption={Semantics classes and data types.}]
707 newtype PrintDict_g v = PrintDict_g (forall a.v a -> String)
708
709 class HasPrint_g d where
710 getPrint_g :: d v -> v a -> String
711
712 instance HasPrint_g PrintDict_g where
713 getPrint_g (PrintDict_g e) = e
714
715 newtype OptDict_g v = OptDict_g (forall a.v a -> v a)
716
717 class HasOpt_g d where
718 getOpt_g :: d v -> v a -> v a
719
720 instance HasOpt_g OptDict_g where
721 getOpt_g (OptDict_g e) = e
722 \end{lstHaskellLhstex}
723
724 \begin{lstHaskellLhstex}[caption={\texorpdfstring{\haskelllhstexinline{GDict}}{GDict} instances}]
725 instance Print_g v => GDict (PrintDict_g v) where
726 gdict = PrintDict_g print_g
727 instance Opt_g v => GDict (OptDict_g v) where
728 gdict = OptDict_g opt_g
729 \end{lstHaskellLhstex}
730
731 \begin{lstHaskellLhstex}[caption={Evaluator instances}]
732 instance HasEval_g d => Eval_g (Expr_g d) where
733 eval_g (Lit_g v) = v
734 eval_g (Add_g e1 e2) = eval_g e1 + eval_g e2
735 eval_g (Ext_g d x) = getEval_g d x
736
737 instance HasEval_g d => Eval_g (Sub_g d) where
738 eval_g (Sub_g e1 e2) = eval_g e1 - eval_g e2
739 eval_g (SubLoop_g e) = eval_g e
740
741 instance HasEval_g d => Eval_g (Neg_g d) where
742 eval_g (Neg_g e) = negate (eval_g e)
743 eval_g (NegLoop_g e) = eval_g e
744
745 instance HasEval_g d => Eval_g (Eq_g d) where
746 eval_g (Eq_g e1 e2) = eval_g e1 == eval_g e2
747 eval_g (EqLoop_g e) = eval_g e
748
749 instance HasEval_g d => Eval_g (Not_g d) where
750 eval_g (Not_g e) = not (eval_g e)
751 eval_g (NotLoop_g e) = eval_g e
752 \end{lstHaskellLhstex}
753
754 \begin{lstHaskellLhstex}[caption={Printer instances}]
755 instance HasPrint_g d => Print_g (Expr_g d) where
756 print_g (Lit_g v) = show v
757 print_g (Add_g e1 e2) = "(" ++ print_g e1 ++ "+" ++ print_g e2 ++ ")"
758 print_g (Ext_g d x) = getPrint_g d x
759
760 instance HasPrint_g d => Print_g (Sub_g d) where
761 print_g (Sub_g e1 e2) = "(" ++ print_g e1 ++ "-" ++ print_g e2 ++ ")"
762 print_g (SubLoop_g e) = print_g e
763
764 instance HasPrint_g d => Print_g (Neg_g d) where
765 print_g (Neg_g e) = "(negate " ++ print_g e ++ ")"
766 print_g (NegLoop_g e) = print_g e
767
768 instance HasPrint_g d => Print_g (Eq_g d) where
769 print_g (Eq_g e1 e2) = "(" ++ print_g e1 ++ "==" ++ print_g e2 ++ ")"
770 print_g (EqLoop_g e) = print_g e
771
772 instance HasPrint_g d => Print_g (Not_g d) where
773 print_g (Not_g e) = "(not " ++ print_g e ++ ")"
774 print_g (NotLoop_g e) = print_g e
775 \end{lstHaskellLhstex}
776
777 \begin{lstHaskellLhstex}[caption={Optimisation instances}]
778 instance HasOpt_g d => Opt_g (Expr_g d) where
779 opt_g (Lit_g v) = Lit_g v
780 opt_g (Add_g e1 e2) = case (opt_g e1, opt_g e2) of
781 (Lit_g 0, e2p ) -> e2p
782 (e1p, Lit_g 0) -> e1p
783 (e1p, e2p ) -> Add_g e1p e2p
784 opt_g (Ext_g d x) = Ext_g d (getOpt_g d x)
785
786 instance HasOpt_g d => Opt_g (Sub_g d) where
787 opt_g (Sub_g e1 e2) = case (opt_g e1, opt_g e2) of
788 (e1p, Lit_g 0) -> SubLoop_g e1p
789 (e1p, e2p ) -> Sub_g e1p e2p
790 opt_g (SubLoop_g e) = SubLoop_g (opt_g e)
791
792 instance (Typeable d, GDict (d (Neg_g d)), HasOpt_g d) => Opt_g (Neg_g d) where
793 opt_g (Neg_g (Add_g e1 e2))
794 = NegLoop_g (Add_g (opt_g (neg_g e1)) (opt_g (neg_g e2)))
795 opt_g (Neg_g (Ext_g d x))
796 = case fromDynamic (toDyn (getOpt_g d x)) of
797 Just (Neg_g e) -> NegLoop_g e
798 _ -> Neg_g (Ext_g d (getOpt_g d x))
799 opt_g (Neg_g e) = Neg_g (opt_g e)
800 opt_g (NegLoop_g e) = NegLoop_g (opt_g e)
801
802 instance HasOpt_g d => Opt_g (Eq_g d) where
803 opt_g (Eq_g e1 e2) = Eq_g (opt_g e1) (opt_g e2)
804 opt_g (EqLoop_g e) = EqLoop_g (opt_g e)
805 \end{lstHaskellLhstex}
806
807 \end{subappendices}
808
809 \input{subfilepostamble}
810 \end{document}