-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtype-expander.hl.rkt
1998 lines (1699 loc) · 79.9 KB
/
type-expander.hl.rkt
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 hyper-literate racket/base #:no-require-lang
@; The #:no-require-lang above is needed because type-expander requires
@; from 'main some identifiers (e.g. λ) which conflict with the re-required
@; racket/base. With this option, we loose arrows in DrRacket for the
@; built-ins in this file, and have otherwise no adverse effects.
@(require scribble-enhanced/doc)
@doc-lib-setup
@(module orig-ids racket/base
(require scribble/manual
(for-label typed/racket/base))
(provide (all-defined-out))
(define orig:: (racket :))
(define orig:let (racket let))
(define orig:→AnyBoolean:Integer (racket (→ Any Boolean : Integer))))
@(require 'orig-ids)
@(unless-preexpanding
(require racket/require
(for-label (submod "..")
(only-in (submod ".." main) colon)
(subtract-in typed/racket/base (submod ".."))
(subtract-in racket typed/racket/base (submod ".."))
racket/require-syntax
racket/provide-syntax
typed/racket/unsafe
racket/format
racket/syntax
syntax/stx
syntax/parse
syntax/parse/experimental/template
syntax/id-table
auto-syntax-e
#;(subtract-in typed-racket/base-env/annotate-classes
(submod "..")))))
@title[#:style manual-doc-style
#:tag "ty-xp-impl"
#:tag-prefix "type-expander/ty-xp-impl"
]{Implementation of the type expander library}
@(chunks-toc-prefix
'("(lib type-expander/scribblings/type-expander-implementation.scrbl)"
"type-expander/ty-xp-impl"))
This document describes the implementation of the
@racketmodname[type-expander] library, using literate
programming. For the library's documentation, see the
@other-doc['(lib "type-expander/scribblings/type-expander.scrbl")]
document instead.
@section{Introduction}
Extensible types would be a nice feature for typed/racket. Unlike
@racket[require] and @racket[provide], which come with
@tc[define-require-syntax] and @tc[define-provide-syntax], and unlike
@tc[match], which comes with @tc[define-match-expander], @tc[typed/racket]
doesn't provide a way to define type expanders. The
@racketmodname[type-expander] library extends @racketmodname[typed/racket]
with the ability to define type expanders, i.e. type-level macros.
The @secref["ty-xp-more" #:tag-prefixes '("type-expander/ty-xp-more")] section
presents a small library of type expanders built upon the mechanism implemented
here.
We redefine the forms @tc[:], @tc[define], @tc[lambda] and so on to
equivalents that support type expanders. Type expanders are defined via the
@tc[define-type-expander] macro. Ideally, this would be handled directly by
@tc[typed/racket], which would directly expand uses of type expanders.
@(table-of-contents)
@section{Expansion model for type expanders}
Type expanders are expanded similarly to macros, with two minor differences:
@itemlist[
@item{A form whose first element is a type expander, e.g.
@racket[(F . args₁)], can expand to the identifier of another type expander
@racket[G]. If the form itself appears as the first element of an outer form,
e.g. @racket[((F . args₁) . args₂)], the first expansion step will result in
@racket[(G . args₂)]. The official macro expander for Racket would then expand
@racket[G] on its own, as an
@tech[#:doc '(lib "scribblings/guide/guide.scrbl")]{identifier macro}, without
passing the @racket[args₂] to it. In contrast, the type expander will expand
the whole @racket[(G . args₂)] form, letting @racket[G] manipulate the
@racket[args₂] arguments.}
@item{It is possible to write anonymous macros,
The @racket[Λ] form can be used to create anonymous type expanders. Anonymous
type expanders are to type expanders what anonymous functions are to function
definitions. The following table presents the expression-level and type-level
function and macro forms. Note that @racket[Let] serves as a type-level
equivalent to both @racket[let] and @racket[let-syntax], as anonymous macros
can be used in conjunction with @racket[Let] to obtain the equivalent of
@racket[let-syntax].
@tabular[#:style 'boxed
#:sep (hspace 1)
#:column-properties '((right-border right) left)
#:row-properties '((bottom-border baseline) (baseline))
(list (list ""
@bold{Definitions}
@bold{Local binding}
@bold{Anonymous functions})
(list @bold{Functions}
@racket[define]
@racket[let]
@racket[λ])
(list @bold{Macros}
@racket[define-syntax]
@racket[let-syntax]
@emph{N/A})
(list @bold{Type‑level functions@superscript{a}}
@racket[define-type]
@racket[Let]
@racket[∀])
(list @bold{Type‑level macros}
@racket[define-type-expander]
@racket[Let]
@racket[Λ]))]
@superscript{a}: The type-level functions are simple substitution functions,
and cannot perform any kind of computation. They are, in a sense, closer to
pattern macros defined with @racket[define-syntax-rule] than to actual
functions.}]
Combined, these features allow some form of "curried" application of type
expanders: The @racket[F] type expander could expand to an anonymous
@racket[Λ] type expander which captures the @racket[args₁] arguments. In the
second expansion step, the @racket[Λ] anonymous type expander would then
consume the @racket[args₂] arguments, allowing @racket[F] to effectively
rewrite the two nested forms, instead of being constrained to the innermost
form.
@subsection{Comparison with TeX's macro expansion model}
For long-time TeX or LaTeX users, this may raise some concerns. TeX programs
are parsed as a stream of tokens. A TeX commands is a macro. When a TeX macro
occurs in the stream of tokens, it takes its arguments by consuming a certain
number of tokens following it. After consuming these arguments, a TeX macro
may expand to another TeX macro, which in turn consumes more arguments. This
feature is commonly used in TeX to implement macros which consume a variable
number arguments: the macro will initially consume a single argument.
Depending on the value of that argument, it will then expand to a macro taking
@racket[_n] arguments, or another macro taking @racket[_m] arguments. This
pattern, omnipresent in any sufficiently large TeX program, opens the door to
an undesirable class of bugs: when a TeX macro invocation appears in the
source code, it is not clear syntactically how many arguments it will
eventually consume. An incorrect parameter value can easily cause it to
consume more arguments than expected. This makes it possible for the macro to
consume the end markers of surrounding environments, for example in the code:
@verbatim|{
\begin{someEnvironment}
\someMacro{arg1}{arg2}
\end{someEnvironment}
}|
the @literal|{someMacro}| command may actually expect three arguments, in
which case it will consume the @literal|{\end}| token, but leave the
@literal|{{someEnvironment}}| token in the stream. This will result in a badly
broken TeX program, which will most likely throw an error complaining that the
environment @literal|{\begin{someEnvironment}}| is not properly closed. The
error may however occur in a completely different location, and may easily
cause a cascade of errors (the missing @literal|{\end{someEnvironment}}| may
cause later TeX commands to be interpreted in a different way, causing them to
misinterpret their arguments, which in turn may cause further errors. The end
result is a series of mysterious error messages somewhat unrelated to the
initial problem.
This problem with TeX macros can be summed up as follows: the number of tokens
following a TeX macro invocation that will be consumed by the macro is
unbounded, and cannot be easily guessed by looking at the raw source code,
despite the presence of programmer-friendly looking syntactic hints, like
wrapping arguments with @literal|{{…}}|.
We argue that the expansion model for type expanders is less prone to this
class of problems, for several reasons:
@itemlist[
@item{Firstly, macros can only consume outer forms if they appear as the
leftmost leaf of the outer form, i.e. while the @racket[F] macro in the
expression
@racketblock[((F . args₁) . args₂)]
may access the @racket[args₂] arguments, it will be constrained within the
@racket[(F . args₁)] in the following code:
@racketblock[(H leading-args₂ (F . args₁) . more-args₂)]
The first case occurs much more rarely than the second, so is less likely to
happen}
@item{Secondly, all TeX macros will consume an arbitrary number of arguments
in a linear fashion until the end of the enclosing group or a paragraph
separation. In contrast, most type expanders will consume all the arguments
within their enclosing application form, and no more. ``Curried'' type
expanders, which expand to a lone macro identifier, will likely only represent
a small subset of all type expanders. For comparison, consider the following
TeX code:
@verbatim|{\CommandOne{argA}\CommandTwo{argB}}|
The @literal|{\CommandOne}| TeX macro might consume zero, one, two three or
more arguments. If it consumes zero arguments, @literal|{{argA}}| will not be
interpreted as an argument, but instead will represent a scoped expression,
similar to @racket[(let () argA)]. If @literal|{\CommandOne}| consumes two or
more arguments, @literal|{\CommandTwo}| will be passed as an argument,
unevaluated, and may be discarded or applied to other arguments than the
seemingly obvious @literal|{{argB}}| argument. The TeX code above could
therefore be equivalent to any the following Racket programs:
@racketblock[
(CommandOne)
(let () argA)
(CommandTwo)
(let () argB)]
@racketblock[
(CommandOne argA)
(CommandTwo)
(let () argB)]
@racketblock[
(CommandOne)
(let () argA)
(CommandTwo argB)]
@racketblock[
(CommandOne argA)
(CommandTwo argB)]
@racketblock[
(CommandOne argA CommandTwo)
(let () argB)]
@racketblock[
(CommandOne argA CommandTwo argB)]
In contrast, the obvious interpretation at a first glance of the TeX program
would be written as follows in Racket:
@racketblock[
(CommandOne argA)
(CommandTwo argB)]
If these appear as ``arguments'' of a larger expression, then their meaning
is unambiguous (unless the larger expression is itself a macro):
@racketblock[
(+ (CommandOne argA)
(CommandTwo argB))]
If however the @racket[(CommandOne argA)] is the first element in its form,
then, if it is a curried macro, it may consume the the
@racket[(CommandTwo argB)] form too:
@racketblock[
((CommandOne argA)
(CommandTwo argB))]
As stated earlier, this case will likely be less common, and it is clearer
that the intent of the programmer to pass @racket[(CommandTwo argB)] as
arguments to the result of @racket[(CommandOne argA)], either as a macro
application or as a regular run-time function application.}
@item{Finally, Racket macros (and type expanders) usually perform a somewhat
thorough check of their arguments, using @racket[syntax-parse] or
@racket[syntax-case] patterns. Arguments to macros and type expanders which do
not have the correct shape will trigger an error early, thereby limiting the
risk of causing errors in cascade.}]
@subsection{Interactions between type expanders and scopes}
Our expansion model for type expanders therefore allows a type expander to
escape the scope in which it was defined before it is actually expanded. For
example, the following type:
@RACKETBLOCK[
(Let ([A Number])
((Let ([F (Λ (self T)
#`(Pairof #,(datum->syntax #'self 'A)
T))])
(Let ([A String])
F))
A))]
first expands to:
@RACKETBLOCK[
(F
A)]
and then expands to:
@RACKETBLOCK[
(Pairof String A)]
and finally expands to:
@RACKETBLOCK[
(Pairof String A)]
Effectively, @racket[F] captures the scope where its name appears (inside all
three @racket[Let] forms), but is expanded in a different context (outside of
the two innermost @racket[Let] forms).
Using Matthew Flatt's notation to indicate the scopes present on an
identifier, we can more explicitly show the expansion steps:
@RACKETBLOCK[
(Let ([A Number])
((Let ([F (Λ (self T)
#`(Pairof #,(datum->syntax #'self 'A)
T))])
(Let ([A String])
F))
A))]
The first @racket[Let] form annotates the identifier it binds with a fresh
scope, numbered @racket[1] here, and adds this scope to all identifiers within
its body. It stores the binding in the @racket[(tl-redirections)] binding
table, as shown by the comment above the code
@RACKETBLOCK[
(code:comment "A¹ := Number")
((Let¹ ([F¹ (Λ¹ (self¹ T¹)
#`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)
T¹))])
(Let¹ ([A¹ String¹])
F¹))
A¹)]
The second @racket[Let] form then binds the @racket[F] identifier, adding a
fresh scope as before:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
((Let¹² ([A¹² String¹²])
F¹²)
A¹)]
The third @racket[Let] form then binds @racket[A] within its body, leaving the
outer @racket[A] unchanged:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
(code:comment "A¹²³ := String¹²")
(F¹²³
A¹)]
The @racket[F¹²³] macro is then expanded, passing as an argument the syntax
object @racket[#'(F¹²³ A¹)]. A fresh scope is added to the identifiers
generated by the macro, in order to enforce macro hygiene. The @racket[A¹]
identifier is passed as an input to the macro, so it is left unchanged, and
@racket[A¹²³] is derived from @racket[F¹²³], via @racket[datum->syntax], and
therefore has the same scopes (@racket[F¹²³] is also a macro input, so it is
not tagged with the fresh scope). The @racket[Pairof¹] identifier, generated by
the macro, is however flagged with the fresh scope @racket[4]. The result of
the application of @racket[F] to this syntax object is:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
(code:comment "A¹²³ := String¹²")
(Pairof¹⁴ A¹²³ A¹)]
The @racket[Pairof¹⁴] type is resolved to the primitive type constructor
@racket[Pairof]:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
(code:comment "A¹²³ := String¹²")
(Pairof A¹²³ A¹)]
The type @racket[A¹²³] is then resolved to @racket[String¹²], which in turn is
resolved to the @racket[String] built-in type:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
(code:comment "A¹²³ := String¹²")
(Pairof String A¹)]
And the type @racket[A¹] is resolved to @racket[Number]:
@RACKETBLOCK[
(code:comment "A¹ := Number")
(code:comment "F¹² := (Λ¹ (self¹ T¹)")
(code:comment " #`(Pairof¹ #,(datum->syntax¹ #'self¹ 'A¹)")
(code:comment " T¹))")
(code:comment "A¹²³ := String¹²")
(Pairof String Number)]
The @racket[syntax-local-value] function does not support querying the
transformer binding of identifiers outside of the lexical scope in which they
are bound. In our case, however, we need to access the transformer binding of
@racket[F¹²³] outside of the scope of the @racket[Let] binding it, and
similarly for @racket[A¹²³].
@section{The @racket[prop:type-expander] structure type property}
Type expanders are identified by the @tc[prop:type-expander]
@tech[#:doc '(lib "scribblings/reference/reference.scrbl")]{structure type
property}. Structure type properties allow the same identifier to act as a
rename transformer, a match expander and a type expander, for example. Such an
identifier would have to implement the @tc[prop:rename-transformer],
@tc[prop:match-expander] and @tc[prop:type-expander] properties, respectively.
@chunk[<prop:type-expander>
(define-values (prop:type-expander
has-prop:type-expander?
get-prop:type-expander-value)
(make-struct-type-property 'type-expander prop-guard))]
The value of the @tc[prop:type-expander] property should either be a
transformer procedure of one or two arguments which will be called when
expanding the type, or the index of a field containing such a procedure.
@chunk[<prop-guard>
(define (prop-guard val struct-type-info-list)
(cond <prop-guard-field-index>
<prop-guard-procedure>
<prop-guard-else-error>))]
If the value is a field index, it should be within bounds. The
@tc[make-struct-field-accessor] function performs this check, and also returns
an accessor. The accessor expects an instance of the struct, and returns the
field's value.
@chunk[<prop-guard-field-index>
[(exact-nonnegative-integer? val)
(let* ([make-struct-accessor (cadddr struct-type-info-list)]
[accessor (make-struct-field-accessor make-struct-accessor val)])
(λ (instance)
(let ([type-expander (accessor instance)])
<prop-guard-field-value>)))]]
The expander procedure will take one argument: the piece of syntax
corresponding to the use of the expander. If the property's value is a
procedure, we therefore check that its arity includes 1.
@chunk[<prop-guard-field-value>
(cond
[(and (procedure? type-expander)
(arity-includes? (procedure-arity type-expander) 2))
(curry type-expander instance)]
[(and (procedure? type-expander)
(arity-includes? (procedure-arity type-expander) 1))
type-expander]
[else
(raise-argument-error 'prop:type-expander-guard
(~a "the value of the " val "-th field should"
" be a procedure whose arity includes 1 or"
" 2")
type-expander)])]
In the first case, when the property value is a field index, we return an
accessor function. The accessor function expects a struct instance, performs
some checks and returns the actual type expander procedure.
When the property's value is directly a type expander procedure, we follow the
same convention. We therefore return a function which, given a struct
instance, returns the type expander procedure (ignoring the @racket[_]
argument).
@chunk[<prop-guard-procedure>
[(procedure? val)
(cond
[(arity-includes? (procedure-arity val) 2)
(λ (s) (curry val s))]
[(arity-includes? (procedure-arity val) 1)
(λ (_) val)]
[else
(raise-argument-error 'prop:type-expander-guard
"a procedure whose arity includes 1 or 2"
val)])]]
When the value of the @racket[prop:type-expander] property is neither a
positive field index nor a procedure, an error is raised:
@chunk[<prop-guard-else-error>
[else
(raise-argument-error
'prop:type-expander-guard
(~a "a procedure whose arity includes 1 or 2, or an exact "
"non-negative integer designating a field index within "
"the structure that should contain a procedure whose "
"arity includes 1 or 2.")
val)]]
@subsection{The @racket[type-expander] struct}
We make a simple struct that implements @tc[prop:type-expander] and nothing
else. It has a single field, @racket[expander-proc], which contains the type
expander transformer procedure.
@chunk[<type-expander-struct>
(struct type-expander (expander-proc) #:transparent
#:extra-constructor-name make-type-expander
#:property prop:type-expander (struct-field-index expander-proc))]
@section{Associating type expanders to identifiers}
@subsection{The @racket[type-expander] syntax class}
The @tc[type-expander] syntax class recognises identifiers
which are bound to type expanders. These fall into three cases:
@itemlist[
@item{The identifier's @racket[syntax-local-value] is an instance of a struct
implementing @racket[prop:type-expander]}
@item{The identifier has been bound by a type-level local binding form like
@racket[Let] or @racket[∀], and therefore are registered in the
@racket[(tl-redirections)] binding table.}
@item{The identifier has been patched via @racket[patch-type-expander], i.e.
a type expander has been globally attached to an existing identifier, in which
case the type expander is stored within the @racket[patched] free identifier
table.}]
@chunk[<expand-type-syntax-classes>
(define-syntax-class type-expander
(pattern local-expander:id
#:when (let ([b (binding-table-find-best (tl-redirections)
#'local-expander
#f)])
(and b (has-prop:type-expander? b)))
#:with code #'local-expander)
(pattern (~var expander
(static has-prop:type-expander? "a type expander"))
#:when (not (binding-table-find-best (tl-redirections)
#'expander
#f))
#:with code #'expander)
(pattern patched-expander:id
#:when (let ([p (free-id-table-ref patched
#'patched-expander
#f)])
(and p (has-prop:type-expander? p)))
#:when (not (binding-table-find-best (tl-redirections)
#'expander
#f))
#:with code #'patched-expander))]
We also define a syntax class which matches types. Since types can bear many
complex cases, and can call type expanders which may accept arbitrary syntax,
we simply define the @tc[type] syntax class as @tc[expr]. Invalid syntax will
be eventually caught while expanding the type, and doing a thorough check
before any processing would only make the type expander slower, with little
actual benefits. The @tc[type] syntax class is however used in syntax patterns
as a form of documentation, to clarify the distinction between types and
run-time or compile-time expressions.
@CHUNK[<type-syntax-class>
(define-syntax-class type
(pattern :expr))]
@chunk[<type-contract>
(define stx-type/c syntax?)]
Finally, we define a convenience syntax class which expands the matched type:
@chunk[<type-expand-syntax-class>
(define-syntax-class type-expand!
#:attributes (expanded)
(pattern t:expr
#:with expanded (expand-type #'t #f)))]
@subsection{Calling type expanders}
The @tc[apply-type-expander] function applies the syntax expander transformer
function associated to @tc[type-expander-id]. It passes @tc[stx] as the single
argument to the transformer function. Usually, @tc[stx] will be the syntax
used to call the type expander, like @tc[#'(te arg ...)] or just @tc[#'te] if
the type expander is not in the first position of a form.
The identifier @tc[type-expander-id] should be bound to a type expander, in
one of the three possible ways described above.
@chunk[<apply-type-expander>
(define/contract (apply-type-expander type-expander-id stx)
(-> identifier? syntax? syntax?)
(let ([val (or (binding-table-find-best (tl-redirections)
type-expander-id
#f)
(let ([slv (syntax-local-value type-expander-id
(λ () #f))])
(and (has-prop:type-expander? slv) slv))
(free-id-table-ref patched type-expander-id #f))]
[ctxx (make-syntax-introducer)])
<apply-type-expander-checks>
(ctxx (((get-prop:type-expander-value val) val) (ctxx stx)))))]
The @racket[apply-type-expander] function checks that its
@racket[type-expander-id] argument is indeed a type expander before attempting
to apply it:
@chunk[<apply-type-expander-checks>
(unless val
(raise-syntax-error 'apply-type-expander
(format "Can't apply ~a, it is not a type expander"
type-expander-id)
stx
type-expander-id))]
@subsection{Associating type expanders to already existing identifiers}
As explained above, existing identifiers which are provided by other libraries
can be ``patched'' so that they behave like type expanders, using a global
table associating existing identifiers to the corresponding expander code:
@chunk[<patched>
(define patched (make-free-id-table))]
@CHUNK[<patch>
(define-syntax patch-type-expander
(syntax-parser
[(_ id:id expander-expr:expr)
#`(begin
(begin-for-syntax
(free-id-table-set! patched
#'id
(type-expander #,(syntax/loc this-syntax
expander-expr)))))]))]
@subsection{Defining new type expanders}
The @tc[define-type-expander] macro binds @tc[_name] to a
type expander which uses @tc[(λ (_arg) . _body)] as the
transformer procedure. To achieve this, we create a
transformer binding (with @tc[define-syntax]), from
@tc[_name] to an instance of the @tc[type-expander]
structure.
@CHUNK[<define-type-expander>
(define-syntax define-type-expander
(syntax-parser
[(_ (name:id arg:id) . body)
#`(define-syntax name
(type-expander #,(syntax/loc this-syntax (λ (arg) . body))))]
[(_ name:id fn:expr)
#`(define-syntax name
(type-expander #,(syntax/loc this-syntax fn)))]))]
@subsection[#:tag "shadow"]{Locally binding type expanders}
Some features of the type expander need to locally bind new type expanders:
@itemlist[
@item{The @racket[(Let ([_id _expr] …) . _body)] special form binds the
identifiers @racket[_id …] to the type expanders @racket[_expr …] in its
@racket[_body].}
@item{When expanding the body of a @racket[(∀ (Tᵢ …) body)] form, the
@racket[Tᵢ] bound by the @racket[∀] may shadow some type expanders with the
same name. If the @racket[∀] form is directly applied to arguments, each
@racket[Tᵢ] is instead bound to the corresponding argument.}
@item{When expanding the body of a @racket[(Rec T body)] form, the @racket[T]
bound by the @racket[Rec] may shadow a type expander with the same name.}]
We use @racket[with-bindings] (defined in another file) to achieve this. The
code
@racketblock[(with-bindings [_bound-ids _transformer-values]
_rebind-stx
_transformer-body)]
evaluates @racket[_transformer-body] in the transformer environment. It
creates a fresh scope, which it applies to the @racket[_bound-ids] and the
@racket[_rebind-stx]. It associates each modified @racket[_bound-id] with the
corresponding @racket[_transformer-value] in the @racket[(tl-redirections)]
binding table. The @racket[with-bindings] form does not mutate the syntax
objects, instead it shadows the syntax pattern variables mentioned in
@racket[_bound-ids] and @racket[_rebind-stx] with versions pointing to the
same syntax objects, but with the fresh scope flipped on them.
The code
@racketblock[(with-rec-bindings [_bound-ids _generate-transformer-values _rhs]
_rebind-stx
_transformer-body)]
works in the same way, but it also flips the fresh scope on each element of
@racket[_rhs]. The @racket[_generate-transformer-values] is expected to be a
transformer expression which, given an element of @racket[_rhs] with the
flipped scope, produces the transformer value to bind to the corresponding
@racket[_bound-id].
The implementation of @racket[with-bindings] unfortunately does not play well
with @racket[syntax-local-value], so the binding table has to be queried
directly instead of using @racket[syntax-local-value]. To our knowledge, the
only ways to make new bindings recognised by @racket[syntax-local-value] are:
@itemlist[
@item{To expand to a @racket[define-syntax] form, followed with a macro
performing the remaining work}
@item{Equivalently, to expand to a @racket[let-syntax] form, whose body is a
macro performing the remaining work}
@item{To call @racket[local-expand] with an internal definition context which
contains the desired bindings}
@item{To explicitly call @racket[syntax-local-value] with an internal
definition context argument}]
It is not practical in our case to use the first solution involving
@racket[define-syntax], as the type expander may be called while expanding an
expression (e.g. @racket[ann]). The next two solutions assume that
@racket[syntax-local-value] will be called in a well-scoped fashion (in the
sense of the official expander): in the second solution,
@racket[syntax-local-value] must be called by expansion-time code located
within the scope of the @racket[let-syntax] form, and in the third solution,
@racket[syntax-local-value] must be called within the dynamic extent of
@racket[local-expand]. The last solution works, but requires that the user
explicitly passes the appropriate internal definition context.
The second and third solutions cannot be applied in our case, because type
expanders can be expanded outside of the scope in which they were defined and
used, as explained the
@secref["Interactions_between_type_expanders_and_scopes"] section.
The current version of the type expander does not support a reliable
alternative to @racket[syntax-local-value] which takes into account local
binding forms for types (@racket[Let], @racket[∀] and @racket[Rec]), but one
could be implemented, either by using some tricks to make the first solution
work, or by providing an equivalent to @racket[syntax-local-value] which
consults the @racket[(tl-redirections)] binding table.
@section{Expanding types}
The @tc[expand-type] function fully expands the type
@tc[stx]. As explained in
@secref["shadow"], shadowing would be better handled using
scopes. The @tc[expand-type] function starts by defining
some syntax classes, then parses @tc[stx], which can fall in
many different cases.
@CHUNK[<expand-type>
(define (expand-type stx [applicable? #f])
(start-tl-redirections
<expand-type-syntax-classes>
(define (expand-type-process stx first-pass?)
<expand-type-debug-before>
((λ (result) <expand-type-debug-after>)
(parameterize (<expand-type-debug-indent>)
<expand-type-debug-rules>
(syntax-parse stx
<expand-type-case-:>
<expand-type-case-expander>
<expand-type-case-∀-later>
<expand-type-case-Λ-later>
<expand-type-case-app-expander>
<expand-type-case-∀-through>
<expand-type-case-Rec>
<expand-type-case-app-Λ>
<expand-type-case-just-Λ/not-applicable>
<expand-type-case-∀-app>
<expand-type-case-Let>
<expand-type-case-Letrec>
<expand-type-case-noexpand>
(code:comment "Must be after other special application cases")
<expand-type-case-app-other>
<expand-type-case-app-fallback>
<expand-type-case-fallback-T>))))
(expand-type-process stx #t)))]
@subsection{Cases handled by @racket[expand-type]}
The cases described below which expand a use of a type expander re-expand the
result, by calling @tc[expand-type] once more. This process is repeated until
no more expansion can be performed. This allows type expanders to produce
calls to other type expanders, exactly like macros can produce calls to other
macros.
We distinguish the expansion of types which will appear as the first element
of their parent form from types which will appear in other places. When the
@racket[applicable?] argument to @racket[expand-type] is @racket[#true], it
indicates that the current type, once expanded, will occur as the first
element of its enclosing form. If the expanded type is the name of a type
expander, or a @racket[∀] or @racket[Λ] form, it will be directly applied to
the given arguments by the type expander. When @racket[applicable?] is
@racket[#false], it indicates that the current type, once expanded, will
@emph{not} appear as the first element of its enclosing form (it will appear
in another position, or it is at the top of the syntax tree representing the
type).
When @racket[applicable?] is @racket[#true], if the type is the name of a type
expander, or a @racket[∀] or @racket[Λ] form, it is not expanded immediately.
Instead, the outer form will expand it with the arguments. Otherwise, these
forms are expanded without arguments, like
@tech[#:doc '(lib "scribblings/guide/guide.scrbl")]{identifier macros} would be.
@subsection{Applying type expanders}
When a type expander is found in a non-applicable position, it is called,
passing the identifier itself to the expander. An
@tech[#:doc '(lib "scribblings/guide/guide.scrbl")]{identifier macro} would be
called in the same way.
@CHUNK[<expand-type-case-expander>
[expander:type-expander
#:when (not applicable?)
(rule id-expander/not-applicable
(let ([ctxx (make-syntax-introducer)])
(expand-type (ctxx (apply-type-expander #'expander.code
(ctxx #'expander)))
applicable?)))]]
When a type expander is found in an applicable position, it is returned
without modification, so that the containing application form may expand it
with arguments. When the expander @racket[e] appears as @racket[(e . args)],
it is applicable. It is also applicable when it appears as
@racket[((Let (bindings…) e) . args)], for example, because @racket[Let]
propagates its @racket[applicable?] status.
@CHUNK[<expand-type-case-expander>
[expander:type-expander
#:when applicable?
(rule id-expander/applicable
#'expander)]]
When a form contains a type expander in its first element, the type expander
is called. The result is re-expanded, so that a type expander can expand to a
use of another type expander.
@CHUNK[<expand-type-case-app-expander>
[(~and expander-call-stx (expander:type-expander . _))
(rule app-expander
(let ([ctxx (make-syntax-introducer)])
(expand-type (ctxx (apply-type-expander #'expander.code
(ctxx #'expander-call-stx)))
applicable?)))]]
When a form of the shape @racket[(_f . _args)] is encountered, and the
@racket[_f] element is not a type expander, the @racket[_f] form is expanded,
and the whole form (with @racket[_f] replaced by its expansion) is expanded a
second time. The @racket[applicable?] parameter is set to @racket[#true] while
expanding @racket[_f], so that if @racket[_f] produces a type expander (e.g.
@racket[_f] has the shape @racket[(Let (…) _some-type-expander)]), the type
expander can be applied to the @racket[_args] arguments.
@CHUNK[<expand-type-case-app-other>
[(~and whole (f . args))
#:when first-pass?
(rule app-other
(expand-type-process
(datum->syntax #'whole
(cons (expand-type #'f #true) #'args)
#'whole
#'whole)
#f))]]
@subsubsection{Polymorphic types with @racket[∀]}
When the @tc[∀] or @tc[All] special forms from @racketmodname[typed/racket]
are used, the bound type variables may shadow some type expanders. The type
expanders used in the body @tc[T] which have the same identifier as a bound
variable will be affected by this (they will not act as a type-expander
anymore). The body of the @tc[∀] or @tc[All] form is expanded with the
modified environment. The result is wrapped again with
@tc[(∀ (TVar …) expanded-T)], in order to conserve the behaviour from
@racketmodname[typed/racket]'s @tc[∀].
@CHUNK[<expand-type-case-∀-through>
[({~and ∀ {~literal ∀}} (tvar:id …) T:type)
#:when (not applicable?)
(rule just-∀/not-applicable
(with-syntax ([(tvar-vars-only …) (remove-ddd #'(tvar …))])
(with-bindings [(tvar-vars-only …) (stx-map <shadowed>
#'(tvar-vars-only …))]
(T tvar …)
#`(∀ (tvar …)
#,(expand-type #'T #f)))))]]
Where @racket[<shadowed>] is used to bind the type variables @racket[tvarᵢ] to
@racket[(No-Expand tvarᵢ)], so that their occurrences are left intact by the
type expander:
@CHUNK[<shadowed>
(λ (__τ)
(make-type-expander
(λ (stx)
(syntax-case stx ()
[self (identifier? #'self) #'(No-Expand self)]
[(self . args) #'((No-Expand self) . args)]))))]
When a @racket[∀] polymorphic type is found in an applicable position, it is
returned without modification, so that the containing application form may
expand it, binding the type parameters to their effective arguments.
@CHUNK[<expand-type-case-∀-later>
[(~and whole ({~literal ∀} (tvar:id …) T:type))
#:when applicable?
(rule just-∀/applicable
#'whole)]]
When a @racket[∀] polymorphic type is immediately applied to arguments, the
type expander attempts to bind the type parameters to the effective arguments.
It currently lacks any support for types under ellipses, and therefore that
case is currently handled by the @racket[<expand-type-case-app-fallback>] case
described later.
@chunk[<expand-type-case-∀-app>
[(({~literal ∀} ({~and tvar:id {~not {~literal …}}} …) τ) arg …)
(unless (= (length (syntax->list #'(tvar …)))
(length (syntax->list #'(arg …))))
<app-args-error>)
(rule app-∀
(with-bindings [(tvar …) (stx-map (λ (a) (make-type-expander (λ (_) a)))
#'(arg …))]
τ
(expand-type #'τ applicable?)))]]
If the given number of arguments does not match the expected number of
arguments, an error is raised immediately:
@chunk[<app-args-error>
(raise-syntax-error
'type-expander
(format (string-append "Wrong number of arguments to "
"polymorphic type: ~a\n"
" expected: ~a\n"
" given: ~a"
" arguments were...:\n")
(syntax->datum #'f)
(length (syntax->list #'(tvar …)))
(length (syntax->list #'(arg …)))
(string-join
(stx-map (λ (a)
(format "~a" (syntax->datum a)))
#'(arg …))
"\n"))
#'whole
#'∀
(syntax->list #'(arg …)))]
@subsubsection{Recursive types with @racket[Rec]}
Similarly, the @tc[Rec] special form will cause the bound
variable @tc[R] to shadow type expanders with the same name,
within the extent of the body @tc[T]. The result is wrapped
again with @tc[(Rec R expanded-T)], in order to conserve the
behaviour from @racketmodname[typed/racket]'s @tc[Rec].
@CHUNK[<expand-type-case-Rec>
[((~literal Rec) R:id T:type)
(rule Rec
#`(Rec R #,(with-bindings [R (<shadowed> #'R)]
T
(expand-type #'T #f))))]]
@subsubsection{Local bindings with @racket[Let] and @racket[Letrec]}
The @tc[Let] special form binds the given identifiers to the corresponding
type expanders. We use @racket[with-bindings], as explained above in
@secref["shadow" #:doc '(lib "type-expander/type-expander.hl.rkt")], to bind
the @racket[Vᵢ …] identifiers to their corresponding @racket[Eᵢ] while
expanding @racket[T].
@CHUNK[<expand-type-case-Let>
[((~commit (~literal Let)) ([Vᵢ:id Eᵢ] …) T:type)
(rule Let
(with-bindings [(Vᵢ …)
(stx-map (λ (Eᵢ)
(make-type-expander
(λ (stx)
(syntax-case stx ()
[self (identifier? #'self) Eᵢ]
[(self . argz) #`(#,Eᵢ . argz)]))))
#'(Eᵢ …))]
T
(expand-type #'T applicable?)))]]
The @tc[Letrec] special form behaves in a similar way, but uses
@racket[with-rec-bindings], so that the right-hand-side expressions
@racket[Eᵢ] appear to be within the scope of all the @racket[Vᵢ] bindings.
@CHUNK[<expand-type-case-Letrec>
[((~commit (~literal Letrec)) ([Vᵢ:id Eᵢ] …) T:type)
(rule Letrec
(with-rec-bindings [(Vᵢ …)
(λ (Eᵢ)
(make-type-expander
(λ (stx)
(syntax-case stx ()
[self (identifier? #'self) Eᵢ]
[(self . args444) #`(#,Eᵢ . args444)]))))
Eᵢ]
T
(expand-type #'T applicable?)))]]