-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path12_language.html
More file actions
511 lines (365 loc) · 64.8 KB
/
12_language.html
File metadata and controls
511 lines (365 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<!doctype html>
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-158904079-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-158904079-1');
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Proyecto: Un Lenguaje de Programación :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script><script>var chapNum = 12;var sandboxLoadFiles = ["code/chapter/12_language.js"];</script></head>
<article>
<nav><a href="11_async.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a></nav>
<h1><span class=chap_num>Chapter 12</span>Proyecto: Un Lenguaje de Programación</h1>
<blockquote>
<p><a class="p_ident" id="p_NCKe5tEBSN" href="#p_NCKe5tEBSN" tabindex="-1" role="presentation"></a>El evaluador, que determina el significado de las expresiones en un lenguaje de programación, es solo otro programa.</p>
<footer>Hal Abelson and Gerald Sussman, <cite>Structure and Interpretation of Computer Programs</cite></footer>
</blockquote>
<p><a class="p_ident" id="p_/UuqC5gn16" href="#p_/UuqC5gn16" tabindex="-1" role="presentation"></a>Construir tu propio lenguaje de programación es sorprendentemente fácil (siempre y cuando no apuntes demasiado alto) y muy esclarecedor.</p>
<p><a class="p_ident" id="p_vypEKNuk0L" href="#p_vypEKNuk0L" tabindex="-1" role="presentation"></a>Lo principal que quiero mostrar en este capítulo es que no hay magia involucrada en la construcción de tu propio lenguaje. A menudo he sentido que algunos inventos humanos eran tan inmensamente inteligentes y complicados que nunca podría llegar a entenderlos. Pero con un poco de lectura y experimentación, a menudo resultan ser bastante mundanos.</p>
<p><a class="p_ident" id="p_Q7++9poilG" href="#p_Q7++9poilG" tabindex="-1" role="presentation"></a>Construiremos un lenguaje de programación llamado Egg. Será un lenguaje pequeño y simple—pero lo suficientemente poderoso como para expresar cualquier computación que puedes pensar. Permitirá una abstracción simple basada en funciones.</p>
<h2 id="parsing"><a class="h_ident" id="h_iAwcitQh1f" href="#h_iAwcitQh1f" tabindex="-1" role="presentation"></a>Análisis</h2>
<p><a class="p_ident" id="p_LWCHgQ8jiK" href="#p_LWCHgQ8jiK" tabindex="-1" role="presentation"></a>La parte más visible de un lenguaje de programación es su <em>sintaxis</em>, o notación. Un <em>analizador</em> es un programa que lee una pieza de texto y produce una estructura de datos que refleja la estructura del programa contenido en ese texto. Si el texto no forma un programa válido, el analizador debe señalar el error.</p>
<p><a class="p_ident" id="p_PDRJRTzhYP" href="#p_PDRJRTzhYP" tabindex="-1" role="presentation"></a>Nuestro lenguaje tendrá una sintaxis simple y uniforme. Todo en Egg es una expresión. Una expresión puede ser el nombre de una vinculación (binding), un número, una cadena de texto o una <em>aplicación</em>. Las aplicaciones son usadas para llamadas de función pero también para constructos como <code>if</code> o <code>while</code>.</p>
<p><a class="p_ident" id="p_ep+0glVGES" href="#p_ep+0glVGES" tabindex="-1" role="presentation"></a>Para mantener el analizador simple, las cadenas en Egg no soportarán nada parecido a escapes de barra invertida. Una cadena es simplemente una secuencia de caracteres que no sean comillas dobles, envueltas en comillas dobles. Un número es un secuencia de dígitos. Los nombres de vinculaciones pueden consistir en cualquier carácter no que sea un espacio en blanco y eso no tiene un significado especial en la sintaxis.</p>
<p><a class="p_ident" id="p_vwvgo3jFhV" href="#p_vwvgo3jFhV" tabindex="-1" role="presentation"></a>Las aplicaciones se escriben tal y como están en JavaScript, poniendo paréntesis después de una expresión y teniendo cualquier cantidad de argumentos entre esos paréntesis, separados por comas.</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_D54Cc06408" href="#c_D54Cc06408" tabindex="-1" role="presentation"></a>hacer(definir(x, 10),
si(>(x, 5),
imprimir("grande"),
imprimir("pequeño")))</pre>
<p><a class="p_ident" id="p_yh0b/fAYIh" href="#p_yh0b/fAYIh" tabindex="-1" role="presentation"></a>La uniformidad del lenguaje Egg significa que las cosas que son operadores en JavaScript (como <code>></code>) son vinculaciones normales en este lenguaje, aplicadas como cualquier función. Y dado que la sintaxis no tiene un concepto de bloque, necesitamos una construcción <code>hacer</code> para representar el hecho de realizar múltiples cosas en secuencia.</p>
<p><a class="p_ident" id="p_CdJy7vtvL6" href="#p_CdJy7vtvL6" tabindex="-1" role="presentation"></a>La estructura de datos que el analizador usará para describir un programa consta de objetos de expresión, cada uno de los cuales tiene una propiedad <code>tipo</code> que indica el tipo de expresión que este es y otras propiedades que describen su contenido.</p>
<p><a class="p_ident" id="p_Enzya6/ZI+" href="#p_Enzya6/ZI+" tabindex="-1" role="presentation"></a>Las expresiones de tipo <code>"valor"</code> representan strings o números literales. Su propiedad <code>valor</code> contiene el string o valor numérico que estos representan. Las expresiones de tipo <code>"palabra"</code> se usan para identificadores (nombres). Dichos objetos tienen una propiedad <code>nombre</code> que contienen el nombre del identificador como un string. Finalmente, las expresiones <code>"aplicar"</code> representan aplicaciones. Tienen una propiedad <code>operador</code> que se refiere a la expresión que está siendo aplicada, y una propiedad <code>argumentos</code> que contiene un array de expresiones de argumentos.</p>
<p><a class="p_ident" id="p_u03uWimuoa" href="#p_u03uWimuoa" tabindex="-1" role="presentation"></a>La parte <code>>(x, 5)</code> del programa anterior se representaría de esta manera:</p>
<pre class="snippet cm-s-default" data-language="application/json" ><a class="c_ident" id="c_y4kHQ33hor" href="#c_y4kHQ33hor" tabindex="-1" role="presentation"></a>{
<span class="cm-property">tipo</span>: <span class="cm-string">"aplicar"</span>,
<span class="cm-property">operador</span>: {<span class="cm-property">tipo</span>: <span class="cm-string">"palabra"</span>, <span class="cm-property">nombre</span>: <span class="cm-string">">"</span>},
<span class="cm-property">argumentos</span>: [
{<span class="cm-property">tipo</span>: <span class="cm-string">"palabra"</span>, <span class="cm-property">nombre</span>: <span class="cm-string">"x"</span>},
{<span class="cm-property">tipo</span>: <span class="cm-string">"valor"</span>, <span class="cm-property">valor</span>: <span class="cm-number">5</span>}
]
}</pre>
<p><a class="p_ident" id="p_ps0Zl+K6zR" href="#p_ps0Zl+K6zR" tabindex="-1" role="presentation"></a>Tal estructura de datos se llama <em>árbol de sintaxis</em>. Si tu imaginas los objetos como puntos y los enlaces entre ellos como líneas entre esos puntos, tiene una forma similar a un árbol. El hecho de que las expresiones contienen otras expresiones, que a su vez pueden contener más expresiones, es similar a la forma en que las ramas de los árboles se dividen y dividen una y otra vez.</p><figure><img src="img/syntax_tree.svg" alt="The structure of a syntax tree"></figure>
<p><a class="p_ident" id="p_UWICD46wH1" href="#p_UWICD46wH1" tabindex="-1" role="presentation"></a>Compara esto con el analizador que escribimos para el formato de archivo de configuración en el <a href="09_regexp.html#ini">Capítulo 9</a>, que tenía una estructura simple: dividía la entrada en líneas y manejaba esas líneas una a la vez. Habían solo unas pocas formas simples que se le permitía tener a una línea.</p>
<p><a class="p_ident" id="p_6Mz6uGItWm" href="#p_6Mz6uGItWm" tabindex="-1" role="presentation"></a>Aquí debemos encontrar un enfoque diferente. Las expresiones no están separadas en líneas, y tienen una estructura recursiva. Las expresiones de aplicaciones <em>contienen</em> otras expresiones.</p>
<p><a class="p_ident" id="p_cXp43eu5PY" href="#p_cXp43eu5PY" tabindex="-1" role="presentation"></a>Afortunadamente, este problema se puede resolver muy bien escribiendo una función analizadora que es recursiva en una manera que refleje la naturaleza recursiva del lenguaje.</p>
<p><a class="p_ident" id="p_LXrIAR63Rl" href="#p_LXrIAR63Rl" tabindex="-1" role="presentation"></a>Definimos una función <code>analizarExpresion</code>, que toma un string como entrada y retorna un objeto que contiene la estructura de datos para la expresión al comienzo del string, junto con la parte del string que queda después de analizar esta expresión Al analizar subexpresiones (el argumento para una aplicación, por ejemplo), esta función puede ser llamada de nuevo, produciendo la expresión del argumento, así como al texto que permanece. A su vez, este texto puede contener más argumentos o puede ser el paréntesis de cierre que finaliza la lista de argumentos.</p>
<p><a class="p_ident" id="p_8Ig2QyzwUD" href="#p_8Ig2QyzwUD" tabindex="-1" role="presentation"></a>Esta es la primera parte del analizador:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_PRn77CBpJZ" href="#c_PRn77CBpJZ" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">analizarExpresion</span>(<span class="cm-def">programa</span>) {
<span class="cm-variable-2">programa</span> <span class="cm-operator">=</span> <span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">programa</span>);
<span class="cm-keyword">let</span> <span class="cm-def">emparejamiento</span>, <span class="cm-def">expresion</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable-2">emparejamiento</span> <span class="cm-operator">=</span> <span class="cm-string-2">/^"([^"]*)"/</span>.<span class="cm-property">exec</span>(<span class="cm-variable-2">programa</span>)) {
<span class="cm-variable-2">expresion</span> <span class="cm-operator">=</span> {<span class="cm-property">tipo</span>: <span class="cm-string">"valor"</span>, <span class="cm-property">valor</span>: <span class="cm-variable-2">emparejamiento</span>[<span class="cm-number">1</span>]};
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">emparejamiento</span> <span class="cm-operator">=</span> <span class="cm-string-2">/^\d+\b/</span>.<span class="cm-property">exec</span>(<span class="cm-variable-2">programa</span>)) {
<span class="cm-variable-2">expresion</span> <span class="cm-operator">=</span> {<span class="cm-property">tipo</span>: <span class="cm-string">"valor"</span>, <span class="cm-property">valor</span>: <span class="cm-variable">Number</span>(<span class="cm-variable-2">emparejamiento</span>[<span class="cm-number">0</span>])};
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">emparejamiento</span> <span class="cm-operator">=</span> <span class="cm-string-2">/^[^\s(),"]+/</span>.<span class="cm-property">exec</span>(<span class="cm-variable-2">programa</span>)) {
<span class="cm-variable-2">expresion</span> <span class="cm-operator">=</span> {<span class="cm-property">tipo</span>: <span class="cm-string">"palabra"</span>, <span class="cm-property">nombre</span>: <span class="cm-variable-2">emparejamiento</span>[<span class="cm-number">0</span>]};
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Sintaxis inesperada: "</span> <span class="cm-operator">+</span> <span class="cm-variable-2">programa</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable">aplicarAnalisis</span>(<span class="cm-variable-2">expresion</span>, <span class="cm-variable-2">programa</span>.<span class="cm-property">slice</span>(<span class="cm-variable-2">emparejamiento</span>[<span class="cm-number">0</span>].<span class="cm-property">length</span>));
}
<span class="cm-keyword">function</span> <span class="cm-def">saltarEspacio</span>(<span class="cm-def">string</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">primero</span> <span class="cm-operator">=</span> <span class="cm-variable-2">string</span>.<span class="cm-property">search</span>(<span class="cm-string-2">/\S/</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">primero</span> <span class="cm-operator">==</span> <span class="cm-operator">-</span><span class="cm-number">1</span>) <span class="cm-keyword">return</span> <span class="cm-string">""</span>;
<span class="cm-keyword">return</span> <span class="cm-variable-2">string</span>.<span class="cm-property">slice</span>(<span class="cm-variable-2">primero</span>);
}</pre>
<p><a class="p_ident" id="p_jBWSCkO4Ej" href="#p_jBWSCkO4Ej" tabindex="-1" role="presentation"></a>Dado que Egg, al igual que JavaScript, permite cualquier cantidad de espacios
en blanco entre sus elementos, tenemos que remover repetidamente los espacios en blanco del inicio del string del programa. Para esto nos ayuda la función <code>saltarEspacio</code>.</p>
<p><a class="p_ident" id="p_og2a2pyEUb" href="#p_og2a2pyEUb" tabindex="-1" role="presentation"></a>Después de saltar cualquier espacio en blanco, <code>analizarExpresion</code> usa tres expresiones regulares para detectar los tres elementos atómicos que Egg soporta: strings, números y palabras. El analizador construye un tipo diferente de estructura de datos dependiendo de cuál coincida. Si la entrada no coincide con ninguna de estas tres formas, la expresión no es válida, y el analizador arroja un error. Usamos <code>SyntaxError</code> en lugar de <code>Error</code> como constructor de excepción, el cual es otro tipo de error estándar, dado que es un poco más específico—también es el tipo de error lanzado cuando se intenta ejecutar un programa de JavaScript no válido.</p>
<p><a class="p_ident" id="p_EgqyXKPX43" href="#p_EgqyXKPX43" tabindex="-1" role="presentation"></a>Luego cortamos la parte que coincidio del string del programa y pasamos eso, junto con el objeto para la expresión, a <code>aplicarAnalisis</code>, el cual verifica si la expresión es una aplicación. Si es así, analiza una lista de los argumentos entre paréntesis.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_fEre6ycrYn" href="#c_fEre6ycrYn" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">aplicarAnalisis</span>(<span class="cm-def">expresion</span>, <span class="cm-def">programa</span>) {
<span class="cm-variable-2">programa</span> <span class="cm-operator">=</span> <span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">programa</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">programa</span>[<span class="cm-number">0</span>] <span class="cm-operator">!=</span> <span class="cm-string">"("</span>) {
<span class="cm-keyword">return</span> {<span class="cm-property">expresion</span>: <span class="cm-variable-2">expresion</span>, <span class="cm-property">resto</span>: <span class="cm-variable-2">programa</span>};
}
<span class="cm-variable-2">programa</span> <span class="cm-operator">=</span> <span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">programa</span>.<span class="cm-property">slice</span>(<span class="cm-number">1</span>));
<span class="cm-variable-2">expresion</span> <span class="cm-operator">=</span> {<span class="cm-property">tipo</span>: <span class="cm-string">"aplicar"</span>, <span class="cm-property">operador</span>: <span class="cm-variable-2">expresion</span>, <span class="cm-property">argumentos</span>: []};
<span class="cm-keyword">while</span> (<span class="cm-variable-2">programa</span>[<span class="cm-number">0</span>] <span class="cm-operator">!=</span> <span class="cm-string">")"</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">argumento</span> <span class="cm-operator">=</span> <span class="cm-variable">analizarExpresion</span>(<span class="cm-variable-2">programa</span>);
<span class="cm-variable-2">expresion</span>.<span class="cm-property">argumentos</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">argumento</span>.<span class="cm-property">expresion</span>);
<span class="cm-variable-2">programa</span> <span class="cm-operator">=</span> <span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">argumento</span>.<span class="cm-property">resto</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">programa</span>[<span class="cm-number">0</span>] <span class="cm-operator">==</span> <span class="cm-string">","</span>) {
<span class="cm-variable-2">programa</span> <span class="cm-operator">=</span> <span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">programa</span>.<span class="cm-property">slice</span>(<span class="cm-number">1</span>));
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">programa</span>[<span class="cm-number">0</span>] <span class="cm-operator">!=</span> <span class="cm-string">")"</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Experaba ',' o ')'"</span>);
}
}
<span class="cm-keyword">return</span> <span class="cm-variable">aplicarAnalisis</span>(<span class="cm-variable-2">expresion</span>, <span class="cm-variable-2">programa</span>.<span class="cm-property">slice</span>(<span class="cm-number">1</span>));
}</pre>
<p><a class="p_ident" id="p_yHMdyzxitq" href="#p_yHMdyzxitq" tabindex="-1" role="presentation"></a>Si el siguiente carácter en el programa no es un paréntesis de apertura, esto no es una aplicación, y <code>aplicarAnalisis</code> retorna la expresión que se le dio.</p>
<p><a class="p_ident" id="p_w//CqZqwyG" href="#p_w//CqZqwyG" tabindex="-1" role="presentation"></a>De lo contrario, salta el paréntesis de apertura y crea el objeto de árbol de sintaxis para esta expresión de aplicación. Entonces, recursivamente llama a <code>analizarExpresion</code> para analizar cada argumento hasta que se encuentre el paréntesis de cierre. La recursión es indirecta, a través de <code>aplicarAnalisis</code> y <code>analizarExpresion</code> llamando una a la otra.</p>
<p><a class="p_ident" id="p_j9Px0Vyqo2" href="#p_j9Px0Vyqo2" tabindex="-1" role="presentation"></a>Dado que una expresión de aplicación puede ser aplicada a sí misma (como en <code>multiplicador(2)(1)</code>), <code>aplicarAnalisis</code> debe, después de haber analizado una aplicación, llamarse asi misma de nuevo para verificar si otro par de paréntesis sigue a continuación.</p>
<p><a class="p_ident" id="p_89g4z+3rO6" href="#p_89g4z+3rO6" tabindex="-1" role="presentation"></a>Esto es todo lo que necesitamos para analizar Egg. Envolvemos esto en una conveniente función <code>analizar</code> que verifica que ha llegado al final del string de entrada después de analizar la expresión (un programa Egg es una sola expresión), y eso nos da la estructura de datos del programa.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_aay8u+BALv" href="#c_aay8u+BALv" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">analizar</span>(<span class="cm-def">programa</span>) {
<span class="cm-keyword">let</span> {<span class="cm-def">expresion</span>, <span class="cm-def">resto</span>} <span class="cm-operator">=</span> <span class="cm-variable">analizarExpresion</span>(<span class="cm-variable-2">programa</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable">saltarEspacio</span>(<span class="cm-variable-2">resto</span>).<span class="cm-property">length</span> <span class="cm-operator">></span> <span class="cm-number">0</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Texto inesperado despues de programa"</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">expresion</span>;
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">analizar</span>(<span class="cm-string">"+(a, 10)"</span>));
<span class="cm-comment">// → {tipo: "aplicar",</span>
<span class="cm-comment">// operador: {tipo: "palabra", nombre: "+"},</span>
<span class="cm-comment">// argumentos: [{tipo: "palabra", nombre: "a"},</span>
<span class="cm-comment">// {tipo: "valor", valor: 10}]}</span></pre>
<p><a class="p_ident" id="p_l7ELJeshJs" href="#p_l7ELJeshJs" tabindex="-1" role="presentation"></a>Funciona! No nos da información muy útil cuando falla y no almacena la línea y la columna en que comienza cada expresión, lo que podría ser útil al informar errores más tarde, pero es lo suficientemente bueno para nuestros propósitos.</p>
<h2><a class="h_ident" id="h_HlYkF24q0q" href="#h_HlYkF24q0q" tabindex="-1" role="presentation"></a>The evaluator</h2>
<p><a class="p_ident" id="p_zhwRUqtrSl" href="#p_zhwRUqtrSl" tabindex="-1" role="presentation"></a>What can we do with the syntax tree for a program? Run it, of course! And that is what the evaluator does. You give it a syntax tree and a scope object that associates names with values, and it will evaluate the expression that the tree represents and return the value that this produces.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_wZARsnj20A" href="#c_wZARsnj20A" tabindex="-1" role="presentation"></a><span class="cm-keyword">const</span> <span class="cm-def">specialForms</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-atom">null</span>);
<span class="cm-keyword">function</span> <span class="cm-def">evaluate</span>(<span class="cm-def">expresion</span>, <span class="cm-def">scope</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">expresion</span>.<span class="cm-property">type</span> <span class="cm-operator">==</span> <span class="cm-string">"value"</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">expresion</span>.<span class="cm-property">value</span>;
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">expresion</span>.<span class="cm-property">type</span> <span class="cm-operator">==</span> <span class="cm-string">"word"</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">expresion</span>.<span class="cm-property">name</span> <span class="cm-keyword">in</span> <span class="cm-variable-2">scope</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">scope</span>[<span class="cm-variable-2">expresion</span>.<span class="cm-property">name</span>];
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">ReferenceError</span>(
<span class="cm-string-2">`Undefined binding: ${</span><span class="cm-variable-2">expresion</span>.<span class="cm-property">name</span><span class="cm-string-2">}</span><span class="cm-string-2">`</span>);
}
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">expresion</span>.<span class="cm-property">type</span> <span class="cm-operator">==</span> <span class="cm-string">"apply"</span>) {
<span class="cm-keyword">let</span> {<span class="cm-def">operator</span>, <span class="cm-def">args</span>} <span class="cm-operator">=</span> <span class="cm-variable-2">expresion</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable-2">operator</span>.<span class="cm-property">type</span> <span class="cm-operator">==</span> <span class="cm-string">"word"</span> <span class="cm-operator">&</span><span class="cm-operator">&</span>
<span class="cm-variable-2">operator</span>.<span class="cm-property">name</span> <span class="cm-keyword">in</span> <span class="cm-variable">specialForms</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">specialForms</span>[<span class="cm-variable-2">operator</span>.<span class="cm-property">name</span>](<span class="cm-variable-2">expresion</span>.<span class="cm-property">args</span>, <span class="cm-variable-2">scope</span>);
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">let</span> <span class="cm-def">op</span> <span class="cm-operator">=</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">operator</span>, <span class="cm-variable-2">scope</span>);
<span class="cm-keyword">if</span> (<span class="cm-keyword">typeof</span> <span class="cm-variable-2">op</span> <span class="cm-operator">==</span> <span class="cm-string">"function"</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">op</span>(<span class="cm-meta">...</span><span class="cm-variable-2">args</span>.<span class="cm-property">map</span>(<span class="cm-def">arg</span> <span class="cm-operator">=></span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">arg</span>, <span class="cm-variable-2">scope</span>)));
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">TypeError</span>(<span class="cm-string">"Applying a non-function."</span>);
}
}
}
}</pre>
<p><a class="p_ident" id="p_iJ+cB7ncAD" href="#p_iJ+cB7ncAD" tabindex="-1" role="presentation"></a>The evaluator has code for each of the expression types. A literal value expression produces its value. (For example, the expression <code>100</code> just evaluates to the number 100.) For a binding, we must check whether it is actually defined in the scope and, if it is, fetch the binding’s value.</p>
<p><a class="p_ident" id="p_NLdaIAcdf6" href="#p_NLdaIAcdf6" tabindex="-1" role="presentation"></a>Applications are more involved. If they are a special form, like <code>if</code>, we do not evaluate anything and pass the argument expressions, along with the scope, to the function that handles this form. If it is a normal call, we evaluate the operator, verify that it is a function, and call it with the evaluated arguments.</p>
<p><a class="p_ident" id="p_6TdgYHF3F3" href="#p_6TdgYHF3F3" tabindex="-1" role="presentation"></a>We use plain JavaScript function values to represent Egg’s function values. We will come back to this <a href="12_language.html#egg_fun">later</a>, when the special form called <code>fun</code> is defined.</p>
<p><a class="p_ident" id="p_wol0KtLeGh" href="#p_wol0KtLeGh" tabindex="-1" role="presentation"></a>The recursive structure of <code>evaluate</code> resembles the similar structure of the parser, and both mirror the structure of the language itself. It would also be possible to integrate the parser with the evaluator and evaluate during parsing, but splitting them up this way makes the program clearer.</p>
<p><a class="p_ident" id="p_lfbXYqM2w2" href="#p_lfbXYqM2w2" tabindex="-1" role="presentation"></a>This is really all that is needed to interpret Egg. It is that simple. But without defining a few special forms and adding some useful values to the environment, you can’t do much with this language yet.</p>
<h2><a class="h_ident" id="h_JOCrYKZbDr" href="#h_JOCrYKZbDr" tabindex="-1" role="presentation"></a>Special forms</h2>
<p><a class="p_ident" id="p_R9YTZoL8Oo" href="#p_R9YTZoL8Oo" tabindex="-1" role="presentation"></a>The <code>specialForms</code> object is used to define special syntax in Egg. It associates words with functions that evaluate such forms. It is currently empty. Let’s add <code>if</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_Qv8/ooeexF" href="#c_Qv8/ooeexF" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">si</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">args</span>.<span class="cm-property">length</span> <span class="cm-operator">!=</span> <span class="cm-number">3</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Wrong number of args to si"</span>);
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">0</span>], <span class="cm-variable-2">scope</span>) <span class="cm-operator">!==</span> <span class="cm-atom">false</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">1</span>], <span class="cm-variable-2">scope</span>);
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">return</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">2</span>], <span class="cm-variable-2">scope</span>);
}
};</pre>
<p><a class="p_ident" id="p_8j6jdyDOpo" href="#p_8j6jdyDOpo" tabindex="-1" role="presentation"></a>Egg’s <code>si</code> construct expects exactly three arguments. It will evaluate the first, and if the result isn’t the value <code>false</code>, it will evaluate the second. Otherwise, the third gets evaluated. This <code>if</code> form is more similar to JavaScript’s ternary <code>?:</code> operator than to JavaScript’s <code>if</code>. It is an expression, not a statement, and it produces a value, namely the result of the second or third argument.</p>
<p><a class="p_ident" id="p_9fjtidVbOZ" href="#p_9fjtidVbOZ" tabindex="-1" role="presentation"></a>Egg also differs from JavaScript in how it handles the condition value to <code>if</code>. It will not treat things like zero or the empty string as false, only the precise value <code>false</code>.</p>
<p><a class="p_ident" id="p_vwKmxnusyS" href="#p_vwKmxnusyS" tabindex="-1" role="presentation"></a>The reason we need to represent <code>if</code> as a special form, rather than a regular function, is that all arguments to functions are evaluated before the function is called, whereas <code>if</code> should evaluate only <em>either</em> its second or its third argument, depending on the value of the first.</p>
<p><a class="p_ident" id="p_QqSon2ioSi" href="#p_QqSon2ioSi" tabindex="-1" role="presentation"></a>The <code>while</code> form is similar.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_wZb+EB+hgA" href="#c_wZb+EB+hgA" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">while</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">args</span>.<span class="cm-property">length</span> <span class="cm-operator">!=</span> <span class="cm-number">2</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Wrong number of args to while"</span>);
}
<span class="cm-keyword">while</span> (<span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">0</span>], <span class="cm-variable-2">scope</span>) <span class="cm-operator">!==</span> <span class="cm-atom">false</span>) {
<span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">1</span>], <span class="cm-variable-2">scope</span>);
}
<span class="cm-comment">// Since undefined does not exist in Egg, we return false,</span>
<span class="cm-comment">// for lack of a meaningful result.</span>
<span class="cm-keyword">return</span> <span class="cm-atom">false</span>;
};</pre>
<p><a class="p_ident" id="p_SIqEJzuMdz" href="#p_SIqEJzuMdz" tabindex="-1" role="presentation"></a>Another basic building block is <code>hacer</code>, which executes all its arguments from top to bottom. Its value is the value produced by the last argument.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_rq/UErwvL/" href="#c_rq/UErwvL/" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">hacer</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">let</span> <span class="cm-def">value</span> <span class="cm-operator">=</span> <span class="cm-atom">false</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">arg</span> <span class="cm-keyword">of</span> <span class="cm-variable-2">args</span>) {
<span class="cm-variable-2">value</span> <span class="cm-operator">=</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">arg</span>, <span class="cm-variable-2">scope</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">value</span>;
};</pre>
<p><a class="p_ident" id="p_KvAMPTVJ2y" href="#p_KvAMPTVJ2y" tabindex="-1" role="presentation"></a>To be able to create bindings and give them new values, we also create a form called <code>definir</code>. It expects a word as its first argument and an expression producing the value to assign to that word as its second argument. Since <code>definir</code>, like everything, is an expression, it must return a value. We’ll make it return the value that was assigned (just like JavaScript’s <code>=</code> operator).</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_s45kC/b6Yq" href="#c_s45kC/b6Yq" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">definir</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">args</span>.<span class="cm-property">length</span> <span class="cm-operator">!=</span> <span class="cm-number">2</span> <span class="cm-operator">|</span><span class="cm-operator">|</span> <span class="cm-variable-2">args</span>[<span class="cm-number">0</span>].<span class="cm-property">type</span> <span class="cm-operator">!=</span> <span class="cm-string">"word"</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Incorrect use of definir"</span>);
}
<span class="cm-keyword">let</span> <span class="cm-def">value</span> <span class="cm-operator">=</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">args</span>[<span class="cm-number">1</span>], <span class="cm-variable-2">scope</span>);
<span class="cm-variable-2">scope</span>[<span class="cm-variable-2">args</span>[<span class="cm-number">0</span>].<span class="cm-property">name</span>] <span class="cm-operator">=</span> <span class="cm-variable-2">value</span>;
<span class="cm-keyword">return</span> <span class="cm-variable-2">value</span>;
};</pre>
<h2><a class="h_ident" id="h_2Tc54fkIgF" href="#h_2Tc54fkIgF" tabindex="-1" role="presentation"></a>The environment</h2>
<p><a class="p_ident" id="p_Mkc8xlkeHk" href="#p_Mkc8xlkeHk" tabindex="-1" role="presentation"></a>The scope accepted by <code>evaluate</code> is an object with properties whose names correspond to binding names and whose values correspond to the values those bindings are bound to. Let’s define an object to represent the global scope.</p>
<p><a class="p_ident" id="p_DNbLZKiE8S" href="#p_DNbLZKiE8S" tabindex="-1" role="presentation"></a>To be able to use the <code>if</code> construct we just defined, we must have access to Boolean values. Since there are only two Boolean values, we do not need special syntax for them. We simply bind two names to the values <code>true</code> and <code>false</code> and use those.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_vJ45zHlK0v" href="#c_vJ45zHlK0v" tabindex="-1" role="presentation"></a><span class="cm-keyword">const</span> <span class="cm-def">topScope</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-atom">null</span>);
<span class="cm-variable">topScope</span>.<span class="cm-property">true</span> <span class="cm-operator">=</span> <span class="cm-atom">true</span>;
<span class="cm-variable">topScope</span>.<span class="cm-property">false</span> <span class="cm-operator">=</span> <span class="cm-atom">false</span>;</pre>
<p><a class="p_ident" id="p_mLmm584R4a" href="#p_mLmm584R4a" tabindex="-1" role="presentation"></a>We can now evaluate a simple expression that negates a Boolean value.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_jQfL+9sOdn" href="#c_jQfL+9sOdn" tabindex="-1" role="presentation"></a><span class="cm-keyword">let</span> <span class="cm-def">prog</span> <span class="cm-operator">=</span> <span class="cm-variable">parse</span>(<span class="cm-string-2">`si(true, false, true)`</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">evaluate</span>(<span class="cm-variable">prog</span>, <span class="cm-variable">topScope</span>));
<span class="cm-comment">// → false</span></pre>
<p><a class="p_ident" id="p_zuRstuTjxo" href="#p_zuRstuTjxo" tabindex="-1" role="presentation"></a>To supply basic arithmetic and comparison operators, we will also add some function values to the scope. In the interest of keeping the code short, we’ll use <code>Function</code> to synthesize a bunch of operator functions in a loop, instead of defining them individually.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_OTgmEw/s8v" href="#c_OTgmEw/s8v" tabindex="-1" role="presentation"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">op</span> <span class="cm-keyword">of</span> [<span class="cm-string">"+"</span>, <span class="cm-string">"-"</span>, <span class="cm-string">"*"</span>, <span class="cm-string">"/"</span>, <span class="cm-string">"=="</span>, <span class="cm-string">"<"</span>, <span class="cm-string">">"</span>]) {
<span class="cm-variable">topScope</span>[<span class="cm-variable">op</span>] <span class="cm-operator">=</span> <span class="cm-variable">Function</span>(<span class="cm-string">"a, b"</span>, <span class="cm-string-2">`return a ${</span><span class="cm-variable">op</span><span class="cm-string-2">}</span> <span class="cm-string-2">b;`</span>);
}</pre>
<p><a class="p_ident" id="p_nv+OyOKpzZ" href="#p_nv+OyOKpzZ" tabindex="-1" role="presentation"></a>A way to output values is also very useful, so we’ll wrap <code>console.log</code> in a function and call it <code>imprimir</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_8TCg/C01nx" href="#c_8TCg/C01nx" tabindex="-1" role="presentation"></a><span class="cm-variable">topScope</span>.<span class="cm-property">imprimir</span> <span class="cm-operator">=</span> <span class="cm-def">value</span> <span class="cm-operator">=></span> {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">value</span>);
<span class="cm-keyword">return</span> <span class="cm-variable-2">value</span>;
};</pre>
<p><a class="p_ident" id="p_+CG1YjXYFG" href="#p_+CG1YjXYFG" tabindex="-1" role="presentation"></a>That gives us enough elementary tools to write simple programs. The following function provides a convenient way to parse a program and run it in a fresh scope.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_bHep5L/R48" href="#c_bHep5L/R48" tabindex="-1" role="presentation"></a><span class="cm-keyword">function</span> <span class="cm-def">run</span>(<span class="cm-def">programa</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable">parse</span>(<span class="cm-variable-2">programa</span>), <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-variable">topScope</span>));
}</pre>
<p><a class="p_ident" id="p_3RSx9KsCbf" href="#p_3RSx9KsCbf" tabindex="-1" role="presentation"></a>We’ll use object prototype chains to represent nested scopes, so that the program can add bindings to its local scope without changing the top-level scope.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_T2thC/hUR+" href="#c_T2thC/hUR+" tabindex="-1" role="presentation"></a><span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(total, 0),</span>
<span class="cm-string-2">definir(count, 1),</span>
<span class="cm-string-2">while(<(count, 11),</span>
<span class="cm-string-2">hacer(definir(total, +(total, count)),</span>
<span class="cm-string-2">definir(count, +(count, 1)))),</span>
<span class="cm-string-2">imprimir(total))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 55</span></pre>
<p><a class="p_ident" id="p_4cQhF2ypgW" href="#p_4cQhF2ypgW" tabindex="-1" role="presentation"></a>This is the program we’ve seen several times before, which computes the sum of the numbers 1 to 10, expressed in Egg. It is clearly uglier than the equivalent JavaScript program—but not bad for a language implemented in less than 150 lines of code.</p>
<h2 id="egg_fun"><a class="h_ident" id="h_K5Yd6h3Axg" href="#h_K5Yd6h3Axg" tabindex="-1" role="presentation"></a>Functions</h2>
<p><a class="p_ident" id="p_r7HIVKVzo4" href="#p_r7HIVKVzo4" tabindex="-1" role="presentation"></a>A programming language without functions is a poor programming language indeed.</p>
<p><a class="p_ident" id="p_OEAPwS9R8Z" href="#p_OEAPwS9R8Z" tabindex="-1" role="presentation"></a>Fortunately, it isn’t hard to add a <code>fun</code> construct, which treats its last argument as the function’s body and uses all arguments before that as the names of the function’s parameters.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_cnvuH0fWH0" href="#c_cnvuH0fWH0" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">fun</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-operator">!</span><span class="cm-variable-2">args</span>.<span class="cm-property">length</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Functions need a body"</span>);
}
<span class="cm-keyword">let</span> <span class="cm-def">body</span> <span class="cm-operator">=</span> <span class="cm-variable-2">args</span>[<span class="cm-variable-2">args</span>.<span class="cm-property">length</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>];
<span class="cm-keyword">let</span> <span class="cm-def">params</span> <span class="cm-operator">=</span> <span class="cm-variable-2">args</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-variable-2">args</span>.<span class="cm-property">length</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>).<span class="cm-property">map</span>(<span class="cm-def">expr</span> <span class="cm-operator">=></span> {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">expr</span>.<span class="cm-property">type</span> <span class="cm-operator">!=</span> <span class="cm-string">"word"</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">SyntaxError</span>(<span class="cm-string">"Parameter names must be words"</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">expr</span>.<span class="cm-property">name</span>;
});
<span class="cm-keyword">return</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">arguments</span>.<span class="cm-property">length</span> <span class="cm-operator">!=</span> <span class="cm-variable-2">params</span>.<span class="cm-property">length</span>) {
<span class="cm-keyword">throw</span> <span class="cm-keyword">new</span> <span class="cm-variable">TypeError</span>(<span class="cm-string">"Wrong number of arguments"</span>);
}
<span class="cm-keyword">let</span> <span class="cm-def">localScope</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-variable-2">scope</span>);
<span class="cm-keyword">for</span> (<span class="cm-keyword">let</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable-2">i</span> <span class="cm-operator"><</span> <span class="cm-variable-2">arguments</span>.<span class="cm-property">length</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>) {
<span class="cm-variable-2">localScope</span>[<span class="cm-variable-2">params</span>[<span class="cm-variable-2">i</span>]] <span class="cm-operator">=</span> <span class="cm-variable-2">arguments</span>[<span class="cm-variable-2">i</span>];
}
<span class="cm-keyword">return</span> <span class="cm-variable">evaluate</span>(<span class="cm-variable-2">body</span>, <span class="cm-variable-2">localScope</span>);
};
};</pre>
<p><a class="p_ident" id="p_KsTEGYhZ+f" href="#p_KsTEGYhZ+f" tabindex="-1" role="presentation"></a>Functions in Egg get their own local scope. The function produced by the <code>fun</code> form creates this local scope and adds the argument bindings to it. It then evaluates the function body in this scope and returns the result.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_eYo1iSFfBf" href="#c_eYo1iSFfBf" tabindex="-1" role="presentation"></a><span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(plusOne, fun(a, +(a, 1))),</span>
<span class="cm-string-2">imprimir(plusOne(10)))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 11</span>
<span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(pow, fun(base, exp,</span>
<span class="cm-string-2">si(==(exp, 0),</span>
<span class="cm-string-2">1,</span>
<span class="cm-string-2">*(base, pow(base, -(exp, 1)))))),</span>
<span class="cm-string-2">imprimir(pow(2, 10)))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 1024</span></pre>
<h2><a class="h_ident" id="h_qtdV3kKVQe" href="#h_qtdV3kKVQe" tabindex="-1" role="presentation"></a>Compilation</h2>
<p><a class="p_ident" id="p_JRcPOXDFEi" href="#p_JRcPOXDFEi" tabindex="-1" role="presentation"></a>What we have built is an interpreter. During evaluation, it acts directly on the representation of the program produced by the parser.</p>
<p><a class="p_ident" id="p_Lk17qNau8L" href="#p_Lk17qNau8L" tabindex="-1" role="presentation"></a><em>Compilation</em> is the process of adding another step between the parsing and the running of a program, which transforms the program into something that can be evaluated more efficiently by doing as much work as possible in advance. For example, in well-designed languages it is obvious, for each use of a binding, which binding is being referred to, without actually running the program. This can be used to avoid looking up the binding by name every time it is accessed, instead directly fetching it from some predetermined memory location.</p>
<p><a class="p_ident" id="p_HrQe0PuoCJ" href="#p_HrQe0PuoCJ" tabindex="-1" role="presentation"></a>Traditionally, compilation involves converting the program to machine code, the raw format that a computer’s processor can execute. But any process that converts a program to a different representation can be thought of as compilation.</p>
<p><a class="p_ident" id="p_+HfDnbf6cY" href="#p_+HfDnbf6cY" tabindex="-1" role="presentation"></a>It would be possible to write an alternative evaluation strategy for Egg, one that first converts the program to a JavaScript program, uses <code>Function</code> to invoke the JavaScript compiler on it, and then runs the result. When done right, this would make Egg run very fast while still being quite simple to implement.</p>
<p><a class="p_ident" id="p_bV8xBkdmzN" href="#p_bV8xBkdmzN" tabindex="-1" role="presentation"></a>If you are interested in this topic and willing to spend some time on it, I encourage you to try to implement such a compiler as an exercise.</p>
<h2><a class="h_ident" id="h_DmDK0dWdfE" href="#h_DmDK0dWdfE" tabindex="-1" role="presentation"></a>Cheating</h2>
<p><a class="p_ident" id="p_WFyw9AWF7D" href="#p_WFyw9AWF7D" tabindex="-1" role="presentation"></a>When we defined <code>if</code> and <code>while</code>, you probably noticed that they were more or less trivial wrappers around JavaScript’s own <code>if</code> and <code>while</code>. Similarly, the values in Egg are just regular old JavaScript values.</p>
<p><a class="p_ident" id="p_qMvm2xpt6o" href="#p_qMvm2xpt6o" tabindex="-1" role="presentation"></a>If you compare the implementation of Egg, built on top of JavaScript, with the amount of work and complexity required to build a programming language directly on the raw functionality provided by a machine, the difference is huge. Regardless, this example hopefully gave you an impression of the way programming languages work.</p>
<p><a class="p_ident" id="p_xuQu2Hdpx2" href="#p_xuQu2Hdpx2" tabindex="-1" role="presentation"></a>And when it comes to getting something done, cheating is more effective than doing everything yourself. Though the toy language in this chapter doesn’t do anything that couldn’t be done better in JavaScript, there <em>are</em> situations where writing small languages helps get real work done.</p>
<p><a class="p_ident" id="p_0TKyk5rWYK" href="#p_0TKyk5rWYK" tabindex="-1" role="presentation"></a>Such a language does not have to resemble a typical programming language. If JavaScript didn’t come equipped with regular expressions, for example, you could write your own parser and evaluator for regular expressions.</p>
<p><a class="p_ident" id="p_fdoy9duCSp" href="#p_fdoy9duCSp" tabindex="-1" role="presentation"></a>Or imagine you are building a giant robotic dinosaur and need to program its behavior. JavaScript might not be the most effective way to do this. You might instead opt for a language that looks like this:</p>
<pre class="snippet cm-s-default" data-language="null" ><a class="c_ident" id="c_831P/I2TjC" href="#c_831P/I2TjC" tabindex="-1" role="presentation"></a>behavior walk
perform when
destination ahead
actions
move left-foot
move right-foot
behavior attack
perform when
Godzilla in-view
actions
fire laser-eyes
launch arm-rockets</pre>
<p><a class="p_ident" id="p_O9+2Ve51P4" href="#p_O9+2Ve51P4" tabindex="-1" role="presentation"></a>This is what is usually called a <em>domain-specific language</em>, a language tailored to express a narrow domain of knowledge. Such a language can be more expressive than a general-purpose language because it is designed to describe exactly the things that need to be described in its domain, and nothing else.</p>
<h2><a class="h_ident" id="h_TcUD2vzyMe" href="#h_TcUD2vzyMe" tabindex="-1" role="presentation"></a>Exercises</h2>
<h3><a class="i_ident" id="i_uQzJv9I1Z6" href="#i_uQzJv9I1Z6" tabindex="-1" role="presentation"></a>Arrays</h3>
<p><a class="p_ident" id="p_tNcRruOv4Q" href="#p_tNcRruOv4Q" tabindex="-1" role="presentation"></a>Add support for arrays to Egg by adding the following three functions to the top scope: <code>array(...values)</code> to construct an array containing the argument values, <code>length(array)</code> to get an array’s length, and <code>element(array, n)</code> to fetch the n<sup>th</sup> element from an array.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_RoeAgWo7vt" href="#c_RoeAgWo7vt" tabindex="-1" role="presentation"></a><span class="cm-comment">// Modify these definitions...</span>
<span class="cm-variable">topScope</span>.<span class="cm-property">array</span> <span class="cm-operator">=</span> <span class="cm-string">"..."</span>;
<span class="cm-variable">topScope</span>.<span class="cm-property">length</span> <span class="cm-operator">=</span> <span class="cm-string">"..."</span>;
<span class="cm-variable">topScope</span>.<span class="cm-property">element</span> <span class="cm-operator">=</span> <span class="cm-string">"..."</span>;
<span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(sum, fun(array,</span>
<span class="cm-string-2">hacer(definir(i, 0),</span>
<span class="cm-string-2">definir(sum, 0),</span>
<span class="cm-string-2">while(<(i, length(array)),</span>
<span class="cm-string-2">hacer(definir(sum, +(sum, element(array, i))),</span>
<span class="cm-string-2">definir(i, +(i, 1)))),</span>
<span class="cm-string-2">sum))),</span>
<span class="cm-string-2">imprimir(sum(array(1, 2, 3))))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 6</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_wvp5VE3wUs" href="#p_wvp5VE3wUs" tabindex="-1" role="presentation"></a>The easiest way to do this is to represent Egg arrays with JavaScript arrays.</p>
<p><a class="p_ident" id="p_pIQgd4yDJ0" href="#p_pIQgd4yDJ0" tabindex="-1" role="presentation"></a>The values added to the top scope must be functions. By using a rest argument (with triple-dot notation), the definition of <code>array</code> can be <em>very</em> simple.</p>
</div></div>
<h3><a class="i_ident" id="i_hOd+yVxaku" href="#i_hOd+yVxaku" tabindex="-1" role="presentation"></a>Closure</h3>
<p><a class="p_ident" id="p_v1H/2L3I5F" href="#p_v1H/2L3I5F" tabindex="-1" role="presentation"></a>The way we have defined <code>fun</code> allows functions in Egg to reference the surrounding scope, allowing the function’s body to use local values that were visible at the time the function was defined, just like JavaScript functions do.</p>
<p><a class="p_ident" id="p_CyqsFIcQdy" href="#p_CyqsFIcQdy" tabindex="-1" role="presentation"></a>The following program illustrates this: function <code>f</code> returns a function that adds its argument to <code>f</code>’s argument, meaning that it needs access to the local scope inside <code>f</code> to be able to use binding <code>a</code>.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_g4apRufRT/" href="#c_g4apRufRT/" tabindex="-1" role="presentation"></a><span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(f, fun(a, fun(b, +(a, b)))),</span>
<span class="cm-string-2">imprimir(f(4)(5)))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 9</span></pre>
<p><a class="p_ident" id="p_40Yj7LMkYl" href="#p_40Yj7LMkYl" tabindex="-1" role="presentation"></a>Go back to the definition of the <code>fun</code> form and explain which mechanism causes this to work.</p>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_LOgpHZsyhJ" href="#p_LOgpHZsyhJ" tabindex="-1" role="presentation"></a>Again, we are riding along on a JavaScript mechanism to get the equivalent feature in Egg. Special forms are passed the local scope in which they are evaluated so that they can evaluate their subforms in that scope. The function returned by <code>fun</code> has access to the <code>scope</code> argument given to its enclosing function and uses that to create the function’s local scope when it is called.</p>
<p><a class="p_ident" id="p_w6RFAh/z4Z" href="#p_w6RFAh/z4Z" tabindex="-1" role="presentation"></a>This means that the prototype of the local scope will be the scope in which the function was created, which makes it possible to access bindings in that scope from the function. This is all there is to implementing closure (though to compile it in a way that is actually efficient, you’d need to do some more work).</p>
</div></div>
<h3><a class="i_ident" id="i_/OBuIOX390" href="#i_/OBuIOX390" tabindex="-1" role="presentation"></a>Comments</h3>
<p><a class="p_ident" id="p_qV4w3Ov/ee" href="#p_qV4w3Ov/ee" tabindex="-1" role="presentation"></a>It would be nice if we could write comments in Egg. For example, whenever we find a hash sign (<code>#</code>), we could treat the rest of the line as a comment and ignore it, similar to <code>//</code> in JavaScript.</p>
<p><a class="p_ident" id="p_EVGdU2vHLH" href="#p_EVGdU2vHLH" tabindex="-1" role="presentation"></a>We do not have to make any big changes to the parser to support this. We can simply change <code>skipSpace</code> to skip comments as if they are whitespace so that all the points where <code>skipSpace</code> is called will now also skip comments. Make this change.</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_HlvQkY82YH" href="#c_HlvQkY82YH" tabindex="-1" role="presentation"></a><span class="cm-comment">// This is the old skipSpace. Modify it...</span>
<span class="cm-keyword">function</span> <span class="cm-def">skipSpace</span>(<span class="cm-def">string</span>) {
<span class="cm-keyword">let</span> <span class="cm-def">first</span> <span class="cm-operator">=</span> <span class="cm-variable-2">string</span>.<span class="cm-property">search</span>(<span class="cm-string-2">/\S/</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">first</span> <span class="cm-operator">==</span> <span class="cm-operator">-</span><span class="cm-number">1</span>) <span class="cm-keyword">return</span> <span class="cm-string">""</span>;
<span class="cm-keyword">return</span> <span class="cm-variable-2">string</span>.<span class="cm-property">slice</span>(<span class="cm-variable-2">first</span>);
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">parse</span>(<span class="cm-string">"# hello\nx"</span>));
<span class="cm-comment">// → {type: "word", name: "x"}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">parse</span>(<span class="cm-string">"a # one\n # two\n()"</span>));
<span class="cm-comment">// → {type: "apply",</span>
<span class="cm-comment">// operator: {type: "word", name: "a"},</span>
<span class="cm-comment">// args: []}</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_Dds6GLJzwb" href="#p_Dds6GLJzwb" tabindex="-1" role="presentation"></a>Make sure your solution handles multiple comments in a row, with potentially whitespace between or after them.</p>
<p><a class="p_ident" id="p_w/PeZhCFV2" href="#p_w/PeZhCFV2" tabindex="-1" role="presentation"></a>A regular expression is probably the easiest way to solve this. Write something that matches “whitespace or a comment, zero or more times”. Use the <code>exec</code> or <code>match</code> method and look at the length of the first element in the returned array (the whole match) to find out how many characters to slice off.</p>
</div></div>
<h3><a class="i_ident" id="i_Y9ZDMshYCQ" href="#i_Y9ZDMshYCQ" tabindex="-1" role="presentation"></a>Fixing scope</h3>
<p><a class="p_ident" id="p_wiUendOwjA" href="#p_wiUendOwjA" tabindex="-1" role="presentation"></a>Currently, the only way to assign a binding a value is <code>definir</code>. This construct acts as a way both to define new bindings and to give existing ones a new value.</p>
<p><a class="p_ident" id="p_O06fqfa6CU" href="#p_O06fqfa6CU" tabindex="-1" role="presentation"></a>This ambiguity causes a problem. When you try to give a nonlocal binding a new value, you will end up defining a local one with the same name instead. Some languages work like this by design, but I’ve always found it an awkward way to handle scope.</p>
<p><a class="p_ident" id="p_wG0OsCIoJb" href="#p_wG0OsCIoJb" tabindex="-1" role="presentation"></a>Add a special form <code>set</code>, similar to <code>definir</code>, which gives a binding a new value, updating the binding in an outer scope if it doesn’t already exist in the inner scope. If the binding is not defined at all, throw a <code>ReferenceError</code> (another standard error type).</p>
<p><a class="p_ident" id="p_vI0CMB91dl" href="#p_vI0CMB91dl" tabindex="-1" role="presentation"></a>The technique of representing scopes as simple objects, which has made things convenient so far, will get in your way a little at this point. You might want to use the <code>Object.<wbr>getPrototypeOf</code> function, which returns the prototype of an object. Also remember that scopes do not derive from <code>Object.prototype</code>, so if you want to call <code>hasOwnProperty</code> on them, you have to use this clumsy expression:</p>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_uQ8XmGT/j0" href="#c_uQ8XmGT/j0" tabindex="-1" role="presentation"></a><span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>.<span class="cm-property">hasOwnProperty</span>.<span class="cm-property">call</span>(<span class="cm-variable">scope</span>, <span class="cm-variable">name</span>);</pre>
<pre class="snippet cm-s-default" data-language="javascript" ><a class="c_ident" id="c_GmoX5LgRIW" href="#c_GmoX5LgRIW" tabindex="-1" role="presentation"></a><span class="cm-variable">specialForms</span>.<span class="cm-property">set</span> <span class="cm-operator">=</span> (<span class="cm-def">args</span>, <span class="cm-def">scope</span>) <span class="cm-operator">=></span> {
<span class="cm-comment">// Your code here.</span>
};
<span class="cm-variable">run</span>(<span class="cm-string-2">`</span>
<span class="cm-string-2">hacer(definir(x, 4),</span>
<span class="cm-string-2">definir(setx, fun(val, set(x, val))),</span>
<span class="cm-string-2">setx(50),</span>
<span class="cm-string-2">imprimir(x))</span>
<span class="cm-string-2">`</span>);
<span class="cm-comment">// → 50</span>
<span class="cm-variable">run</span>(<span class="cm-string-2">`set(quux, true)`</span>);
<span class="cm-comment">// → Some kind of ReferenceError</span></pre>
<div class="solution"><div class="solution-text">
<p><a class="p_ident" id="p_NhXhfFLedb" href="#p_NhXhfFLedb" tabindex="-1" role="presentation"></a>You will have to loop through one scope at a time, using <code>Object.<wbr>getPrototypeOf</code> to go the next outer scope. For each scope, use <code>hasOwnProperty</code> to find out whether the binding, indicated by the <code>name</code> property of the first argument to <code>set</code>, exists in that scope. If it does, set it to the result of evaluating the second argument to <code>set</code> and then return that value.</p>
<p><a class="p_ident" id="p_vdMHRjshzJ" href="#p_vdMHRjshzJ" tabindex="-1" role="presentation"></a>If the outermost scope is reached (<code>Object.<wbr>getPrototypeOf</code> returns null) and we haven’t found the binding yet, it doesn’t exist, and an error should be thrown.</p>
</div></div><nav><a href="11_async.html" title="previous chapter">◀</a> <a href="index.html" title="cover">◆</a></nav>
</article>