-
Notifications
You must be signed in to change notification settings - Fork 14
/
tutorial.scrbl
2535 lines (2066 loc) · 88.7 KB
/
tutorial.scrbl
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#lang scribble/manual
@(require "ex.rkt"
"bib.rkt")
@(require scribble/core
scribble/html-properties
racket/date
(for-label (except-in racket _ add1 sub1 ... λ + * -> string any)
(except-in redex I O)))
@(require racket/sandbox
scribble/examples)
@(define (make-eval . tops)
(call-with-trusted-sandbox-configuration
(lambda ()
(parameterize ([sandbox-output 'string]
[sandbox-error-output 'string])
(let ([the-eval (make-base-eval)])
(for ([s tops]) (the-eval s))
the-eval)))))
@(define redex-eval
(make-eval
'(require redex/reduction-semantics redex/pict racket/set #;redex/reduction-semantics redex-aam-tutorial/tutorial)))
@(define-syntax-rule (eg d ...)
(examples #:label #f #:eval redex-eval d ...))
@elem[#:style
(style #f (list (alt-tag "a")
(attributes
'((href . "https://github.com/dvanhorn/redex-aam-tutorial/")))))
@elem[#:style
(style #f
(list (alt-tag "img")
(attributes
'((style . "position: absolute; top: 0; right: 0; border: 0;")
(src . "https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67")
(alt . "Fork me on GitHub")
(data-canonical-src . "https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png")))))]]
@title{An Introduction to Redex with Abstracting Abstract Machines (v0.6)}
@author+email["David Van Horn" "[email protected]"]
Last updated: @date->string[(current-date)]
@section{Introduction}
@margin-note{This is a ``living'' artifact: please submit bug reports
and pull requests whenever you spot problems in this document.
@url{https://github.com/dvanhorn/redex-aam-tutorial/}}
This article provides a brief introduction to the Redex programming
language for semantic modelling. It does so by developing several
semantic models of a simple programming language and then showing how
to construct a program analyzer for this language using the
``Abstracting Abstract Machines'' method@~cite[bib:aam].
So this tutorial aims to accomplish two goals:
@itemlist[
@item{(1) to introduce semantic engineers (programming language
researchers, language designers and implementors, analysis and tool
builders, etc.) to the Redex programming language;}
@item{(2) to demonstrate the method of building abstract interpreters
known as AAM.}
]
You could read this tutorial for either purpose. If you want to learn
Redex, this tutorial will build a bunch of standard semantic systems:
reduction relations, type judgments, evaluators, machines, and finally
a program analyzer. If you want an explicit and approachable
introduction to the AAM method, this tutorial will walk you through a
detailed construction.
@subsection{What is Redex?}
Redex@~cite[bib:redex] is a scripting language and set of associated tools supporting
the conception, design, construction, and testing of semantic systems
such as programming languages, type systems, program logics, and
program analyses. As a scripting language, it enables an engineer to
create executable specifications of common semantic elements such as
grammars, reduction relations, judgments, and metafunctions; the basic
elements of formal systems. It includes a number of software
engineering inspired features to make models robust and includes tools
for typesetting models and generating algebraic steppers for exploring
program behaviors. In brief, Redex supports all phases of the
semantic engineering life-cycle.
@margin-note{For an excellent talk motivating Redex, see the video of
Robby Findler's
@emph{@hyperlink["https://www.youtube.com/watch?v=BuCRToctmw0"]{Run
Your Research}} talk at POPL 2012 @~cite[bib:run-your-research].}
I have used Redex since its first release and it has played a critical
role in several of my research projects. It has allowed me to rapidly
explore new ideas, hypothesize claims, and---typically---refute these
claims and refine the ideas. In some cases, Redex has eased the
development of research; I can go from idea to result much faster and
more effectively than I could without Redex. In other cases, using
Redex has illuminated problems I did not know existed, leading to new
results and research. But in other cases, I simply @emph{could not
have accomplished my research without Redex}.
Redex has become such an integral tool in my research that I cannot
imagine my research path without it. It has changed the way I
approach and think about problems.
@subsection{What is Abstracting Abstract Machines?}
Abstracting Abstract Machines (or AAM, for short) is a method for
systematically constructing sound program analyzers. The central idea
is that a programming language's semantics can be transformed, by a
simple turn-the-crank construction, into an analysis for soundly
reasoning about programs written in that language. It has been used
to analyze a number of language features often considered beyond the
pale of existing analysis approaches. A key advantage of the approach
is that ideas from programming language design and implementation can
be directly imported and applied to the design and implementation of
abstract interpreters.
@subsection{Prerequisites}
This tutorial assumes you have some experience with programming
language semantic artifacts such as grammars, reduction relations,
evaluation relations, typing judgments. If you have never seen these
before, you should probably start with a graduate PL text book
(e.g.@~cite[bib:redex]). It does not assume you have a background in
program analysis or abstract interpretation.
This tutorial also assumes you have some experience with programming
in a Lisp-like language. In particular, you should be comfortable
with the concepts behind @racket[quote], @racket[quasiquote], and
@racket[unquote]. Having programmed with pattern matching would also
help.
You will need @hyperlink["http://racket-lang.org/"]{Racket}, which is
very easy to install and works on all major operating systems. At the
time of writing, version 6.9 is the latest release.
You can download the source code for this tutorial here:
@url{https://github.com/dvanhorn/redex-aam-tutorial/archive/master.zip}.
@section{Warmup}
Redex, at its core, is a language for defining and operating on
s-expressions that is equiped with a powerful pattern matching
mechanism.
@margin-note{To follow along with this tutorial, you must `(require redex)` immediately below your `#lang racket` definition in DrRacket.}
An s-expression is a potentially nested piece of data that may include
numbers, booleans, symbols, and lists of s-expressions. Before
getting in to how to model semantics with Redex, let's just play with
some simple examples.
S-expressions are constructed with the @racket[term] form:
@eg[
(term 2)
(term fred)
(term ())
(term (fred (2) (() green)))
]
If you've ever programmed with a language in the LISP family, you can
first think of @racket[term] as being synonymous with @racket[quote].
A @deftech{language} is a set of s-expressions, defined by the
@racket[define-language] form. For example:
@eg[
(define-language L
(M ::= N F (M ...))
(F ::= fred wilma)
(N ::= 2 7))]
This defines the language @racket[L]. The language @racket[L] is
inductively defined as the smallest set such that @racketresult[2],
@racketresult[7], @racketresult[fred], and @racketresult[wilma] are in
@racket[L], and if some values @emph{x@subscript{0}} through
@emph{x@subscript{n}} are in @racket[L], then the list containing
@emph{x@subscript{0}} through @emph{x@subscript{n}} is in @racket[L].
@margin-note{The use of capital letters for non-terminals is just a
convention I follow and not a requirement of Redex.}
The definition of @racket[L] takes the familiar form of a BNF-like
grammar. The ``@racket[...]'' postfix operator indicates zero or
more repetitions of the preceding pattern.
In addition to @racket[L], this grammar also carves out
subsets of @racket[L] defined by the non-terminals of the grammar,
namely @racket[M], @racket[F], and @racket[N]. The non-terminal names
are significant because they become pattern variables which can be
used to match against elements of the language.
The simplest operation is to ask whether an s-expression is an element
of one of these sets. For example:
@eg[
(redex-match? L N (term 2))
(redex-match? L N (term 9))
(redex-match? L N (term fred))
(redex-match? L M (term (((((((fred)))))))))
]
In general, @racket[redex-match?] can use an arbitrary pattern, not
just a non-terminal name:
@eg[
(redex-match? L (N ...) (term 2))
(redex-match? L (N ...) (term (7 2 7)))
(redex-match? L (M_1 M_2) (term (7 (2 fred))))
]
The last example demonstrates the use of subscripts in patterns, which
serve to distinguish multiple occurrences of the same non-terminal
name. Had we left of the subscripts, the pattern would only match
lists of two @emph{identical} terms:
@eg[
(redex-match? L (M M) (term (7 (2 fred))))
(redex-match? L (M M) (term ((2 fred) (2 fred))))
]
We can also define functions on terms, called @deftech{metafunctions}
using the @racket[define-metafunction] form. A metafunction is given
by an ordered sequence of pattern and template clauses. For example,
here is a function that swaps occurrences of @racketresult[fred] and
@racketresult[wilma]:
@eg[
(define-metafunction L
swap : M -> M
[(swap fred) wilma]
[(swap wilma) fred]
[(swap (M ...)) ((swap M) ...)]
[(swap M) M])
]
There are two imporant things to notice in this example: (1) the
clauses of metafunction definitions are ordered, so the last clause
matches only if the first three do not; (2) the use of
``@racket[...]'' can also occur on the right-hand side of clauses, so
the third clause distributes the @racket[swap] call to all of the
elements of the list.
Now we can see the difference between @racket[quote] and
@racket[term]: within the @racket[term] form, metafunctions are
interpreted:
@eg[
(term (swap (wilma fred)))
(eval:alts (code:quote (swap (wilma fred))) '(swap (wilma fred)))
(term (7 (swap (wilma 2 (fred)))))
]
It's important to note that metafunction exist within Redex terms and
are not functions in the host language. Refering to metafunctions
outside of @racket[term] causes a syntax error:
@eg[
(eval:error (swap wilma))
]
Now that we have seen the basics, we can move on to a real example.
@section{PCF}
Let's start by building a model of a very simple, typed functional
programming language based on the PCF language@~cite[bib:pcf].
Although simple, PCF contains all the essential elements of a real
programming language. Scaling the approach of these notes up to a
more sophisticated language is just a small matter of semantic
hacking.
PCF is a core typed functional programming language. For values, it
includes natural numbers, functions, and primitive operations. Terms
include variables, values, applications, conditionals, and recursive
functions.
@eg[
(define-language PCF
(M ::=
N O X L
(μ (X : T) L)
(M M ...)
(if0 M M M))
(X ::= variable-not-otherwise-mentioned)
(L ::= (λ ([X : T] ...) M))
(V ::= N O L)
(N ::= number)
(O ::= O1 O2)
(O1 ::= add1 sub1)
(O2 ::= + *)
(T ::= num (T ... -> T)))
]
@margin-note{Greek symbols: you can enter Greek symbols in the
DrRacket IDE by typing many common LaTeX commands followed by
Control-\ (in OS X). For example ``\sigma'' plus Control-\ will enter
``σ''. To make things easier, you can type a unique prefix, so ``\sig''
plus Control-\ will also enter a ``σ'' as well.}
Compared with the warmup example, there's really not much to point
other than the use of @racket[variable-not-otherwise-mentioned], which
is just a shorthand way of saying what's @emph{not} a variable name;
in particular, any symbol mentioned in the grammar cannot be a
variable name, so for example @racketresult[λ], @racketresult[μ],
@racketresult[if0], @racketresult[:], etc., cannot be used as variable
names. (Had we just used @racket[variable] instead of
@racket[variable-not-otherwise-mentioned], nothing would break (yet),
but it would be ambiguous as to whether some expressions were
applications or lambda abstractions. Down the line, that probably
will break some of the claims we expect to hold on the language.)
One thing that is missing from the grammar is the requirement that
@racketresult[λ]-bound variables are distinct. We could express this
side condition in the grammar, but instead we'll defer this
requirement to the typing judgment (which we'll see next).
As an example PCF program, here is a program that computes the
factorial of 5:
@eg[
(define-term fact-5
((μ (fact : (num -> num))
(λ ([n : num])
(if0 n
1
(* n (fact (sub1 n))))))
5))
]
(The @racket[define-term] form is way to bind a name interpreted
within @racket[term].)
We can write a test to make sure that this program is indeed in the
language @racket[PCF]:
@eg[
(test-equal (redex-match? PCF M (term fact-5)) #t)]
@subsection{Typing judgement}
Let's now define a typing relation for PCF programs. The typing
relation will, as usual, be defined in terms of a typing environment,
which is missing from the PCF grammar. Rather than revising the
grammar, we can define a @deftech{language extension} as follows:
@eg[
(define-extended-language PCFT PCF
(Γ ::= ((X T) ...)))
]
The @racket[PCFT] language includes everything in the @racket[PCF]
language, plus a notion of type environments @racket[Γ], which are
sequences of variable and type pairs. (Language extensions can also
replace or augment existing non-terminals, as we'll see later.)
Let's first take a detour to develop some useful, general purpose
helper functions.
Association lists, like @racket[Γ], come up again and again, so let's
define a few operations for them. Since association lists are more
general than type environments, we'll want to define generic versions
of this operations. In order to be generic, we should only use the
built-in patterns of Redex and not the metavariables of languages we
define. To accomodate this, we first define the language of built-in
patterns:
@eg[
(define-language REDEX)
]
This definition introduces no non-terminals, so it includes only the
built-in patterns like @racket[number], @racket[variable],
@racket[...], etc. When we define generic operations, we will define
them in the language of @racket[REDEX].
First, let's write a straightforward recursive judgment form that
relates a given key to all its associations:
@eg[
(define-judgment-form REDEX
#:mode (lookup I I O)
#:contract (lookup ((any any) ...) any any)
[(lookup (_ ... (any any_0) _ ...) any any_0)])
]
This relation makes use of the @racket[any] pattern, which ranges
over all values. It also uses the @racket[_] pattern, which like
@racket[any], will match anything, but unlike @racket[any] it is not a
binder and therefore (1) it cannot be used on the right hand side and
(2) multiple occurrences of @racket[_] on the left hand side are not
constrained to match the same thing.
The clause uses a non-linear pattern to require a binding to match the
given key (notice the two left-hand occurrences of @racket[any]).
@eg[
(judgment-holds (lookup ((x 1) (y 2) (x 3)) x 1))
(judgment-holds (lookup ((x 1) (y 2) (x 3)) x 2))
(judgment-holds (lookup ((x 1) (y 2) (x 3)) x 3))
(judgment-holds (lookup ((x 1) (y 2) (x 3)) x any) any)
]
In addition to looking up an association, we need an operation to
extend an association list. A simple definition that allows for an
association to be extended with an arbitrary number of key-value pairs
is then:
@eg[
(define-metafunction REDEX
ext1 : ((any any) ...) (any any) -> ((any any) ...)
[(ext1 (any_0 ... (any_k any_v0) any_1 ...) (any_k any_v1))
(any_0 ... (any_k any_v1) any_1 ...)]
[(ext1 (any_0 ...) (any_k any_v1))
((any_k any_v1) any_0 ...)])
(define-metafunction REDEX
ext : ((any any) ...) (any any) ... -> ((any any) ...)
[(ext any) any]
[(ext any any_0 any_1 ...)
(ext1 (ext any any_1 ...) any_0)])
]
The @racket[ext] metafunction overrides an existing association, if
there is one; otherwise it prepends the new association to the list.
Lastly, we will want to assert that @racket[λ]-bound variables are
unique, so let's define a @racket[unique] predicate, which holds when
its arguments are distinct:
@eg[
(define-metafunction REDEX
unique : (any ...) -> boolean
[(unique (any_!_1 ...)) #t]
[(unique (_ ...)) #f])
]
This defines a @racket[unique] metafunction that takes a list of
any number of elements and produces @racket[#t] when they are unique and
@racket[#f] otherwise. This uses a new kind of pattern, which uses
the @tt{_!} naming prefix. The meaning of this pattern is that
repeated uses of it must be distinct, thus @racket[any_!_1 ...]
matches disjoint sequences.
@eg[
(term (unique ()))
(term (unique (1)))
(term (unique (1 2)))
(term (unique (1 2 3 2)))
]
There is a kind of short-hand for defining predicates (metafunctions
that produce either true or false), called, confusingly enough,
@racket[define-relation]:
@eg[
(define-relation REDEX
unique ⊆ (any ...)
[(unique (any_!_1 ...))])
]
It can be used just like a metafunction:
@eg[
(term (unique (1 2)))
(term (unique (1 2 3 2)))
]
With these generic operations in place, we can now define the typing
relation ``@racket[⊢]'':
@eg[
(define-judgment-form PCFT
#:mode (⊢ I I I O)
#:contract (⊢ Γ M : T)
[(lookup Γ X T)
-------------- var
(⊢ Γ X : T)]
[------------- num
(⊢ Γ N : num)]
[----------------------- op1
(⊢ Γ O1 : (num -> num))]
[--------------------------- op2
(⊢ Γ O2 : (num num -> num))]
[(⊢ Γ M_1 : num)
(⊢ Γ M_2 : T)
(⊢ Γ M_3 : T)
--------------------------- if0
(⊢ Γ (if0 M_1 M_2 M_3) : T)]
[(⊢ (ext Γ (X T)) L : T)
----------------------- μ
(⊢ Γ (μ (X : T) L) : T)]
[(⊢ Γ M_0 : (T_1 ..._1 -> T))
(⊢ Γ M_1 : T_1) ...
----------------------- app
(⊢ Γ (M_0 M_1 ..._1) : T)]
[(unique (X ...))
(⊢ (ext Γ (X T) ...) M : T_n)
------------------------------------------ λ
(⊢ Γ (λ ([X : T] ...) M) : (T ... -> T_n))])
]
The @racket[define-judgment-form] specifies a @deftech{relation}.
Conceptually, a relation in Redex is a function from inputs to sets of
outputs and the definition of a relation must specify which positions
of the relation are inputs and which are outputs, as seen in the
@racket[#:mode] spec. This relation has three inputs (although the
last one is always the constant ``@racketresult[:]'' to make the form
easier to read) and one output. The two real inputs are the type
environment and term; the output is the type. The @racket[#:contract]
annotation specifies the signature of the relation.
A relation is specifed by a number of clauses. Each clause has some
number of hypotheses (calls to this or other judgments) and side
conditions (noted with @racket[where]), followed by a line, an
optional name, and a conclusion. Unlike metafunctions, the clauses
are unordered and therefore may overlap.
Judgments must be ``well-moded''. If some variable appears in an
output position of a conclusion but cannot be determined based on
inputs or outputs of hypotheses, a static error will be signalled.
Judgments can be used either with the @racket[judgment-holds] form or
from other judgment definitions or metafunctions. The
@racket[judgment-holds] form works as follows:
@;This prevents us, for example, from leaving off type annotations on
@;@racket[λ]-bound variables and ``guessing'' them in the type judgment.
@eg[
(judgment-holds (⊢ () (λ ([x : num]) x) : (num -> num)))
]
This use specifies a type @racketresult[(num -> num)] and verifies this type
is in the typing relation.
Alternatively, we can use a metavariable in the type position in
order to compute all of the types this term has. This metavariable is
bound to these types in the scope of the following term which, in this
case is just @racket[T]. Consequently the result is the list of types
for this program.
@eg[
(judgment-holds (⊢ () (λ ([x : num]) x) : T) T)
(judgment-holds (⊢ () fact-5 : T) T)
]
It's possible to illustrate judgments as follows:
@eg[
(eval:alts
(show-derivations
(build-derivations
(⊢ () (λ ([x : num]) (add1 x)) : T)))
(void))
]
@image[#:suffixes '(".pdf" ".png")]{img/show-derivations}
We can verify that ill-formed lambda-abstractions have no type:
@eg[
(judgment-holds (⊢ () (λ ([x : num] [x : num]) x) : T) T)
]
Enough types, let's calculate!
@subsection{The calculus of PCF}
To calculate with PCF programs, we start by formulating a
@deftech{reduction relation} that captures the axioms of reduction for
PCF:
@(redex-eval '(require redex-aam-tutorial/shared))
@; Forward place holder definition
@(redex-eval
'(define-judgment-form PCF
#:mode (δ I O)
#:contract (δ (O N ...) N)
[(δ (+ N_0 N_1) ,(+ (term N_0) (term N_1)))]
[(δ (* N_0 N_1) ,(* (term N_0) (term N_1)))]
[(δ (sub1 N) ,(sub1 (term N)))]
[(δ (add1 N) ,(add1 (term N)))]))
@eg[
(define r
(reduction-relation
PCF #:domain M
(--> (μ (X : T) M)
(subst (X (μ (X : T) M)) M)
μ)
(--> ((λ ([X : T] ...) M_0) M ...)
(subst (X M) ... M_0)
β)
(--> (O N_0 ...) N_1
(judgment-holds (δ (O N_0 ...) N_1))
δ)
(--> (if0 0 M_1 M_2) M_1 if-t)
(--> (if0 N M_1 M_2) M_2
(side-condition (not (zero? (term N))))
if-f)))
]
A reduction relation defines a binary relation on terms in a given
domain, in this case terms @racket[M]. A reduction relation is
defined by a number of clauses, noted with @racket[-->], which consist
of a left-hand side, a right-hand side, any number of side conditions,
and optional name. The order of clauses is irrelevant and like
judgments, clauses may overlap.
@margin-note{
Even though reduction relations are relations, and conceptually can be
thought of as a judgment with @racket[#:mode (r I O)] and
@racket[#:contract (r M M)], they are considered different from
Redex's point of view and support different operations.}
This definition relies on two auxilary definitions: a @racket[δ]
relation for interpreting primitive operations and a @racket[subst]
metafunction which implements substitution.
@eg[
(define-judgment-form PCF
#:mode (δ I O)
#:contract (δ (O N ...) N)
[(δ (+ N_0 N_1) ,(+ (term N_0) (term N_1)))]
[(δ (* N_0 N_1) ,(* (term N_0) (term N_1)))]
[(δ (sub1 N) ,(sub1 (term N)))]
[(δ (add1 N) ,(add1 (term N)))])
]
Note that this judgment omits the horizontal lines, which are in fact
optional (but conclusions precede hypotheses when omitted; of course
it makes no difference when there are no hypotheses as is the case
with @racket[δ]). It also uses @racket[unquote], written
``@tt{,}'' to escape out of Redex and into Racket. Thus the
interpration of PCF's @racketresult[+] is given by Racket's @racket[+]
function, and likewise for the rest of the operations.
The substitution operation is straightforward, if a bit tedious. We
defer it to an appendix and future models will simply avoid the need
for subsitution. If you'd like, you can install this package on the
command line: @commandline{$ raco pkg install redex-aam-tutorial} and
then import the @racket[subst] metafunction as follows:
@eg[
(require redex-aam-tutorial/subst)
(term (subst (x 5) (y 7) (+ x y)))
]
We can now use @racket[apply-reduction-relation] to see the results of
applying the @racket[r] reduction relation to a term:
@eg[
(apply-reduction-relation r (term (add1 5)))
(apply-reduction-relation r (term ((λ ([x : num]) x) (add1 5))))
(apply-reduction-relation r (term (sub1 ((λ ([x : num]) x) (add1 5)))))
]
The second example shows that @racket[apply-reduction-relation] only
takes @emph{one} step of computation since clearly @racketresult[(add1
5)] can reduce further. The third example shows that reduction can
only occur at the outermost term; despite having multiple redexes
inside the term, the term itself does not reduce.
Using @racket[apply-reduction-relation*] will take any number of steps
and return the set of irreducible terms:
@eg[
(apply-reduction-relation* r (term (add1 5)))
(apply-reduction-relation* r (term ((λ ([x : num]) x) (add1 5))))
(apply-reduction-relation* r (term (sub1 ((λ ([x : num]) x) (add1 5)))))
]
Of course, the reflexive, transitive closure of @racket[r], which is
what @racket[apply-reduction-relation*] computes, still does not
enable reductions within terms, so the last example does not reduce.
We could define another reduction relation which incorporates progress
rules. Alternatively, we can use operations to compute such a
relation from @racket[r]:
@eg[
(compatible-closure r PCF M)
]
This example of the @racket[compatible-closure] operation computes a
new relation that allows @racket[r] to be applied anywhere within a
term @racket[M]:
@eg[
(define -->r (compatible-closure r PCF M))
(apply-reduction-relation* -->r (term ((λ ([x : num]) x) (add1 5))))
(apply-reduction-relation* -->r (term (sub1 ((λ ([x : num]) x) (add1 5)))))
]
It's also possible to visualize each step of reduction using the
@racket[traces] function, which launches a window showing each path of
reduction. For example:
@eg[
(eval:alts (traces -->r (term ((λ ([x : num]) x) (add1 5)))) (void))
]
produces:
@image[#:suffixes '(".pdf" ".png") #:scale .8]{img/reduction}
Notice that the @racket[traces] window visualizes all possible
reduction sequences.
@subsection{Call-by-value and call-by-name: Strategies, contexts, and axioms}
It is possible to consider reduction @emph{strategies} which fix a
deterministic order to reductions. One way to represent such a
strategy is to define a grammar of @deftech{evaluation contexts} that
restrict where the reduction relation @racket[r] may be applied.
For example, to obtain a reduction strategy that always reduces the
left-most, outer-most redex, we can define evaluation context as
follows:
@eg[
(define-extended-language PCFn PCF
(E ::= hole
(E M ...)
(O V ... E M ...)
(if0 E M M)))
]
Now using @racket[context-closure], we can compute a relation that
does the left-most, outer-most call-by-name reduction.
@eg[
(define -->n
(context-closure r PCFn E))
]
@eg[
(eval:alts (traces -->n (term ((λ ([x : num]) x) (add1 5)))) (void))
]
@image[#:suffixes '(".pdf" ".png") #:scale .8]{img/cbn-reduction}
Unlike @racket[-->r], we can use @racket[-->n] to calculate
@racket[fact-5]:
@eg[
(apply-reduction-relation* -->n (term fact-5))
]
We can also turn the example into a unit test:
@eg[
(test-->> -->n (term fact-5) 120)
]
While we can't use @racket[apply-reduction-relation*] to compute
@racket[fact-5] with @racket[-->r], we can test @racket[-->r] with
@racket[test-->>∃], which tests for reachability:
@eg[
(test-->>∃ -->r (term fact-5) 120)
]
@margin-note{Why doesn't @racket[(apply-reduction-relation* -->r (term
fact-5))] produce an answer?}
In addition to call-by-name, we can also characterize left-most,
outer-most call-by-value reduction with the following strategy and a
restriction of the @racket[β] axiom:
@eg[
(define-extended-language PCFv PCF
(E ::= hole
(V ... E M ...)
(if0 E M M)))
(define v
(extend-reduction-relation
r PCF #:domain M
(--> ((λ ([X : T] ...) M_0) V ...)
(subst (X V) ... M_0)
β)))
(define -->v
(context-closure v PCFv E))
]
Notice that @racket[v] is defined as an
@racket[extended-reduction-relation] of @racket[r]. An extension of a
reduction relation can add additional reduction cases or override
existing ones, as is the case here, by providing a new rule with the
same name as an existing one.
Like @racket[-->n], the @racket[-->v] relation defines a deterministic
reduction strategy, but it differs from @racket[-->n] in @emph{where}
it reduces and @emph{what} it reduces:
@eg[
(eval:alts (traces -->v (term ((λ ([x : num]) x) (add1 5)))) (void))
]
@image[#:suffixes '(".pdf" ".png") #:scale .8]{img/cbv-reduction}
And like @racket[-->n], it produces an answer for @racket[fact-5]:
@eg[
(apply-reduction-relation* -->v (term fact-5))
]
If the relations @racket[-->n] and @racket[-->v] produce answers, they
are consistent with each other, but the @racket[-->n] relation
produces more answers than @racket[-->v] as the following examples
demonstrate:
@eg[
(define-term Ω
((μ (loop : (num -> num))
(λ ([x : num])
(loop x)))
0))
(apply-reduction-relation* -->n (term ((λ ([x : num]) 0) Ω)))
(apply-reduction-relation* -->v (term ((λ ([x : num]) 0) Ω)))
]
These examples also show that Redex terminates, even when the
reduction of a term has a cycle in it.
@subsection{Evaluation}
As an alternative to the reduction-based approach of the previous
subsection, computation is often characterized by a compositional
evaluation function. This approach avoids substitution and instead
represents substitutions lazily with a @deftech{closure}, which is a
term paired with an environment mapping variable names to values:
@eg[
(define-extended-language PCF⇓ PCF
(V ::= N O (L ρ) ((μ (X : T) L) ρ))
(ρ ::= ((X V) ...)))
]
Like type environments, value environments are instances of
association lists, so we will use the generic @racket[lookup] and
@racket[ext] operations.
The evaluation function @racket[⇓] can now be defined as a judgment as
follows:
@eg[
(define-judgment-form PCF⇓
#:mode (⇓ I I I O)
#:contract (⇓ M ρ : V)
[(⇓ N ρ : N)]
[(⇓ O ρ : O)]
[(⇓ L ρ : (L ρ))]
[(⇓ (μ (X_f : T_f) L) ρ : ((μ (X_f : T_f) L) ρ))]
[(lookup ρ X V)
--------------
(⇓ X ρ : V)]
[(⇓ M_0 ρ : N)
(where M ,(if (zero? (term N)) (term M_1) (term M_2)))
(⇓ M ρ : V)
---------------------------
(⇓ (if0 M_0 M_1 M_2) ρ : V)]
[(⇓ M_0 ρ : O)
(⇓ M_1 ρ : N)
...
(δ (O N ...) N_1)
-----------------------
(⇓ (M_0 M_1 ...) ρ : N_1)]
[(⇓ M_0 ρ : ((λ ([X_1 : T] ...) M) ρ_1))
(⇓ M_1 ρ : V_1)
...
(⇓ M (ext ρ_1 (X_1 V_1) ...) : V)
-----------------------------------
(⇓ (M_0 M_1 ...) ρ : V)]
[(⇓ M_0 ρ : (name f ((μ (X_f : T_f) (λ ([X_1 : T] ...) M)) ρ_1)))
(⇓ M_1 ρ : V_1)
...
(⇓ M (ext ρ_1 (X_f f) (X_1 V_1) ...) : V)
-----------------------------------------
(⇓ (M_0 M_1 ...) ρ : V)])
]
We can use it to compute examples:
@eg[
(judgment-holds (⇓ fact-5 () : V) V)
]
Or test:
@eg[
(test-equal (judgment-holds (⇓ fact-5 () : 120)) #t)
]
@subsection{A brief aside on the caveats of language extensions}
Redex, as we've seen, has some powerful features to support extension,
and this tutorial uses them, well, @emph{extensively}. However, there
are some gothchas worth being aware of.
One of the most prominent gotchas is the mixing of reduction relation
extensions and metafunctions (or relations).
When a reduction relation is extended, the original relation is
reinterpreted over the new language; thus the original pattern
variables of the original definition may take on new meaning. So for
example, consider this simple language and reduction relation:
@eg[
(define-language L0 (M ::= number))
(define r0 (reduction-relation L0 (--> M 5)))
(apply-reduction-relation r0 (term 7))
]
Suppose we then extend @racket[L0] by overriding the meaning of
@racket[M] to include strings:
@eg[
(define-extended-language L1 L0 (M ::= .... string))
]
We can create an extension of @racket[r0] that is the reinterpretation
of @racket[r0] over this new meaning of @racket[M]:
@eg[
(define r0′ (extend-reduction-relation r0 L1))
]
This works just fine and @racket[r0′] reduces as expected when applied
to strings:
@eg[
(apply-reduction-relation r0′ "seven")
]
However, let's consider an alternative, seemingly equivalent
development of the base relation that involves a metafunction:
@eg[
(define-metafunction L0
to-five : M -> M
[(to-five M) 5])
(define r1 (reduction-relation L0 (--> M (to-five M))))
(apply-reduction-relation r1 (term 7))
(define r1′ (extend-reduction-relation r1 L1))
]
You might expect that the extension of @racket[r1] to @racket[L1]
would also reinterpret the definition of @racket[to-five], but it does
not. Consequently, applying @racket[r1′] to a string results in a
run-time domain error from applying @racket[to-five] to a string:
@eg[
(eval:error (apply-reduction-relation r1′ "seven"))
]
Relaxing the contract on @racket[to-five] is no help either; using a
more relaxed contract such as @racket[any -> any] would shift the
error to a failure to match since the @racket[M] in the definition of
@racket[to-five] is still an @racket[M] in @racket[L0] and thus
doesn't match strings.
But isn't there a mechanism for extending metafunctions? Yes. There
is @racket[define-metafunction/extension], which allows you to define a
@racket[L1] compatible version of @racket[to-five]:
@eg[
(define-metafunction/extension to-five L1
to-five/L1 : M -> M)
(term (to-five/L1 "seven"))
]
This defines a new metafunction, @racket[to-five/L1], which
reinterprets the definition of @racket[to-five] over @racket[L1]. (We
could aslo have added clauses to this definition, which are